Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON data in php without knowing key value

Tags:

json

php

firebase

I need to read firebase JSON URL in php and then display it. My firebase has got below .json data:

{"dDsdE4AlB7P5YYd4fWbYTQKCLPh1":{"email":"[email protected]","name":"abhishek"},
 "z1ceiLhdh9YVu7lGnVvqDWoWHFH3":{"email":"[email protected]","name":"ravish"},
 "ghg76JHG8jhkj7GHGJ763kjhFF45":{"email":"[email protected]","name":"John"}}

I am able to access "name" field using the key value, as below:-

$url = 'https://xxxx.firebaseio.com/users.json'; // path to JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data); // decode the JSON feed

echo $characters->dDsdE4AlB7P5YYd4fWbYTQKCLPh1->name;

Now, how to access "name" field without knowing the key value? Because these keys are automatically generated by firebase and could be any value.

Many thanks in advance!

like image 229
Abhishek Kashyap Avatar asked Mar 08 '23 22:03

Abhishek Kashyap


2 Answers

Make an associative array from your json. Then you can traverse it using foreach with keys and values. That way you will have the key value also the associated data to the key.

$characters = json_decode($data, 1);

foreach ($characters as $key => $value) {
    echo $key . ' ' . $echo $value['name'];
}
like image 130
sshopov Avatar answered Mar 10 '23 12:03

sshopov


You could also try to get the keys themselves:

array_keys($yourEncodedJson);

This will return all key names in the provided array.

This way, you won't need to loop through them.

like image 23
jens1o Avatar answered Mar 10 '23 11:03

jens1o