Reputation: 1747
how to parse following json in php
[
{ "user":"John", "age":22, "country":"United States" },
{ "user":"Will", "age":27, "country":"United Kingdom" },
{ "user":"Abiel", "age":19, "country":"Mexico" },
{ "user":"Rick", "age":34, "country":"Panama" },
{ "user":"Susan", "age":23, "country":"Germany" },
{ "user":"Amy", "age":43, "country":"France" }
]
i use the following code for this but it didnt work
$jsonData = file_get_contents("http://localhost/attendance1/a.json");
$phpArray = json_decode($jsonData, true);
echo $phpArray;
foreach ($phpArray as $key => $value) {
echo "<h2>$key</h2>";
foreach ($value as $k => $v) {
echo "$k | $v <br />";
}
}
Upvotes: 1
Views: 154
Reputation: 473
[
{ "user":"John", "age":22, "country":"United States" },
{ "user":"Will", "age":27, "country":"United Kingdom" },
{ "user":"Abiel", "age":19, "country":"Mexico" },
{ "user":"Rick", "age":34, "country":"Panama" },
{ "user":"Susan", "age":23, "country":"Germany" },
{ "user":"Amy", "age":43, "country":"France" }
]
the format is like an array
$array = [3,5,7,4]
which prints like
Array ( [0] => 3 [1] => 5 [2] => 7 [3] => 4 )
and elements accessed a $array{index}
In the same way using loop you should access the elements and then you can use the function json_decode.
$object = json_decode($element_of_array)
which returns an object using that object you can access data from json element.
$object->user
$object->age
hope this would be helpful for you, Good Luck!
Upvotes: 0
Reputation: 656
you have to change your json primary item to array (instead object) using [ ] instead { }.
[
{ "user":"John", "age":22, "country":"United States" },
{ "user":"Will", "age":27, "country":"United Kingdom" },
{ "user":"Abiel", "age":19, "country":"Mexico" },
{ "user":"Rick", "age":34, "country":"Panama" },
{ "user":"Susan", "age":23, "country":"Germany" },
{ "user":"Amy", "age":43, "country":"France" }
]
Upvotes: 3
Reputation: 3396
it's not a valid JSON Format, try this:
[
{ "user":"John", "age":22, "country":"United States" },
{ "user":"Will", "age":27, "country":"United Kingdom" },
{ "user":"Abiel", "age":19, "country":"Mexico" },
{ "user":"Rick", "age":34, "country":"Panama" },
{ "user":"Susan", "age":23, "country":"Germany" },
{ "user":"Amy", "age":43, "country":"France" }
]
(look at square brackets)
"[]" brackets indicates a LIST, while "{}" indicates an object. The difference between them is that objects contains "key":"value" pairs, while lists return items without a key
Upvotes: 1