-1

I have the following JSON array, unfortunately the objects are not being nested in a larger parent so I am unsure how to parse the object.

JSON Array:

[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]

Currently I have done the following, which is just echoing 0 and 1:

$json = '[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo $key;
}

But I would like to access the values of name and id on every foreach, how can the be done?

Daniel
  • 1
  • 6
  • 13

2 Answers2

0
echo $value["id"]." ".$value["name"];

should do it (within your loop), just like any associative array values.

ADyson
  • 51,527
  • 13
  • 48
  • 61
0

This works for me:

$json = '[{"name":"Jacob","id":4},{"name":"Mandy","id":3}]';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    $name = $value['name'];
    $id = $value['id'];

    // do whatever you want with $name and $id
}
sensorario
  • 18,131
  • 26
  • 91
  • 148
  • Thank you for the help, if you don't mind can you please take a look at my other question: https://stackoverflow.com/questions/70735685/how-to-keep-only-unique-objects-in-json-array-php – Daniel Jan 17 '22 at 01:59