I have the following JSON object:
$json = '{
"Name": "Peter",
"countries": {
"France": {
"A": "1",
"B": "2"
},
"Germany": {
"A": "10",
"B": "20"
},
....
}
}';
I want to parse the properties of the object in the property "countries" like an array. In Javascript I would the lodash function values. Is there in PHP any function to do that easily?
This is probably a duplicate.
Here's what you need:
$array = json_decode($json, true);
json_decode parses a json object. The true option tells it to return an associative array instead of an object.
To access the countries info specifically:
foreach ($array["countries"] as $ci) {
//do something with data
}
See the manual for more info: http://php.net/manual/en/function.json-decode.php
editing to add a good point in another answer: you can access the key and value with the foreach if you need the country names as well. like so:
foreach ($array["countries"] as $country => $info) {
//do something with data
}
You can simply parse the string to json using json_decode and use object notation like this:
$countries = json_decode($json)->countries;
//do anything with $countries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With