I have the following problem with my foreach since I am consuming a function that returns an associative array:
var_dump($respuesta);
array(7) { ["Codigo"]=> string(2) "28" ["NumeroCaja"]=> string(1) "2" ["Productos"]=> string(102) "[{"total": "1099", "descripcion": "Samsung"}, {"descripcion": "Galaxy A01"}, {"descripcion": "Negro"}]" ["Fecha"]=> string(10) "2022-03-29" ["Total"]=> string(4) "1099" ["Comision3%"]=> string(3) "500" ["Comision5%"]=> string(3) "600" }
and I try to iterate in my foreach as follows:
foreach ($respuesta as $val) {
echo $val['Codigo'];
}
and it throws me this error: Warning: Illegal string offset 'Codigo' , I understand that it must be because it is not associating well or does not know that $val has a "Codigo" association, so how can I assign it.
The array is
$respuesta
. When you go through it with thatforeach
,$val
it takes the value of each element of the array. Therefore,$val
it is not an array, and it does not have an element'Codigo'
, hence the error.I think you don't need the
foreach
, you would if you had an array of responses.In any case, depending on what you have, you can access the
'Codigo'
response element directly:Or you can do a
foreach
to show all the elements of$respuesta
:On the other hand, if you wanted to display the products, you just have to access the element
'Productos'
of your array$respuesta
. But its content is a JSON, so if you want to handle it in PHP you will have to convert it:$productos
yes it will be an array, there it does make senseforeach
if you wanted to do something with the products one by one.But
$respuesta
it is a one-dimensional array, if it were multidimensional, that is, an array of responses, then it would make sense to go through it to collect the data for each response.Note .- Consult the documentation
json_decode
if you have never used that function, to fully understand what it returns. In the example that I have given you, it will be an array of objects. But if you pass it a second parameter ittrue
will be an array of arrays.