Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Parse properties of an Object like an Array

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?

like image 949
MrScf Avatar asked Jan 27 '26 04:01

MrScf


2 Answers

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
}
like image 105
TCooper Avatar answered Jan 28 '26 17:01

TCooper


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
like image 25
Aniket Sahrawat Avatar answered Jan 28 '26 18:01

Aniket Sahrawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!