Home > OS >  Issue parsing both values in JSON array | PHP
Issue parsing both values in JSON array | PHP

Time:01-17

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?

CodePudding user response:

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

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

CodePudding user response:

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
}
  •  Tags:  
  • Related