-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?

John
  • 965
  • 8
  • 16
  • `$value` is the object, so youll need `echo $value->id` – 0stone0 Jan 16 '22 at 21:48
  • each element is an assoc array, so: `echo $value['name'].PHP_EOL;` – felipsmartins Jan 16 '22 at 21:49
  • @felipsmartins can you please take a look at this question? I appreciate your help: https://stackoverflow.com/questions/70735685/how-to-keep-only-unique-objects-in-json-array-php – John Jan 17 '22 at 02:00

2 Answers2

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

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

ADyson
  • 57,178
  • 14
  • 51
  • 63
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
  • 20,262
  • 30
  • 97
  • 159
  • 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 – John Jan 17 '22 at 01:59