3

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?

1

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

are you sure about that part of your code: $json->json_...?
@Jeff oops! Thanks!
countries is not an array. It is an object. I did following:$data = json_decode($json, true);foreach ($data["countries"] as $info) {
@MrScf If you use json_decode($json, true) then you get a associative array and hence you can use echo $info['A']
1

array_keys does the same basic thing as Lodash's _.values appears to.

$obj = json_decode($json, true); // cause you want properties, not substrings :P
$keys = array_keys($obj['countries']);

// $keys is now ['France', 'Germany', ...]

In PHP, though, you can get the key and value at the same time.

foreach ($obj['countries'] as $country => $info) {
    // $country is 'France', then 'Germany', then...
    // $info is ['A' => 1, 'B' => 2], then ['A' => 10, 'B' => 20], then...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.