Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving array keys from JSON input

I have this array:

$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');

and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:

id
name
age

How can I do this?

like image 384
Nick Avatar asked Jun 06 '12 12:06

Nick


People also ask

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.

How do I iterate through a key in JSON?

We can use Object. entries() to convert a JSON array to an iterable array of keys and values. Object. entries(obj) will return an iterable multidimensional array.

Can JSON keys be arrays?

A JSON value can be an object, array, number, string, true, false, or null, and JSON structure can be nested up to any level.


2 Answers

Try it

foreach($json->entries as $row) {
    foreach($row as $key => $val) {
        echo $key . ': ' . $val;
        echo '<br>';
    }
}

In the $key you shall get the key names and in the val you shal get the values

like image 75
Sena Avatar answered Sep 23 '22 05:09

Sena


You could do something like this:

foreach($json->entries as $record){
    echo $record->id;
    echo $record->name;
    echo $record->age;
}

If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.

like image 32
Emmanuel Okeke Avatar answered Sep 25 '22 05:09

Emmanuel Okeke