I make a query via API and as a response I get a JSON
which I store in a variable and convert it into an Array:
$items = json_decode( $access__resultado, true );
I print a part of the Array (the one that interests me) as follows:
echo "<pre>";
print_r( $items["accesses"] );
echo "</pre>";
And it gives me the following result:
Array (
[0] => Array (
[access_id] => 8o5THPq8mofa
)
[1] => Array (
[access_id] => mmBAHc107Unp
)
[2] => Array (
[access_id] => gDDOyPQIXH60
)
)
How can I loop through it to get the value of each access_id
? I have tried the following ways, but it doesn't show me anything:
$accesses = $items["accesses"]; // Opción 1
$accesses = $items->accesses; // Opción 2
foreach ( $accesses as $val ) {
echo $value["access_id"]; // Opción 1
echo $value->access_id; // Opción 2
}
In the foreach loop, the first $accesses element is the sub-arrsy you want to loop through. On the right side of the 'as' you define the variable $val, which is going to be each element. In this case each $val contains an access_id key.
Therefore, within your loop you must access $val and not $value, which is not defined in your example. Put inside your loop: