MrScf
MrScf

Reputation: 2497

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?

Upvotes: 3

Views: 535

Answers (3)

TCooper
TCooper

Reputation: 1900

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
}

Upvotes: 4

cHao
cHao

Reputation: 86506

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...
}

Upvotes: 1

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

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

Upvotes: 2

Related Questions