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

3
  • $value is the object, so youll need echo $value->id Commented Jan 16, 2022 at 21:48
  • each element is an assoc array, so: echo $value['name'].PHP_EOL; Commented Jan 16, 2022 at 21:49
  • @felipsmartins can you please take a look at this question? I appreciate your help: stackoverflow.com/questions/70735685/… Commented Jan 17, 2022 at 2:00

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help, if you don't mind can you please take a look at my other question: stackoverflow.com/questions/70735685/…
0
echo $value["id"]." ".$value["name"];

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.