Marcatectura Marcatectura - 4 months ago 11
PHP Question

PHP Only Returning Last JSON Object

I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason

json_decode
is only returning the last item in the JSON array. Here's the JSON:

{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}


And the PHP:

<?php

//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);

var_dump($filey);

?>


The result is only the last item in the array:

array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)


Using
json_last_error
returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.

I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?

Answer

That's because your json object names "person" within json array are similar so json decode will override the values with latest. Consider something like

{
  "person1": {
    "lname": "smith",
    "fname": "bob"
  },
  "person2": {
    "lname": "jones",
    "fname": "jane"
  }
}

and your code will work fine.