Reputation: 1695
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?
Upvotes: 0
Views: 122
Reputation: 40896
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode
to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true)
will give me the array shape I expect.
Happy coding.
Upvotes: 1
Reputation: 113
When you use json_decode(true)
, your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true)
, then change "person" to "person1" or so.
Try both var_dump($filey)
and var_dump($json)
, you will see what I'm talking about.
Upvotes: 0
Reputation: 8339
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.
Upvotes: 2