如何在不知道键值的情况下在php中读取JSON数据

时间:2017-10-02 11:58:37

标签: php json firebase

我需要在php中读取firebase JSON URL然后显示它。 我的firebase已经低于.json数据:

{"dDsdE4AlB7P5YYd4fWbYTQKCLPh1":{"email":"abhi@gmail.com","name":"abhishek"},
 "z1ceiLhdh9YVu7lGnVvqDWoWHFH3":{"email":"ravi@gmail.com","name":"ravish"},
 "ghg76JHG8jhkj7GHGJ763kjhFF45":{"email":"John@gmail.com","name":"John"}}

我可以访问" name"使用键值的字段,如下所示: -

$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;

现在,如何访问" name"字段不知道键值?因为这些密钥是由firebase自动生成的,可以是任何值。

非常感谢提前!

2 个答案:

答案 0 :(得分:6)

从你的json创建一个关联数组。然后,您可以使用带有键和值的foreach遍历它。这样,您将获得键值以及键的关联数据。

$characters = json_decode($data, 1);

foreach ($characters as $key => $value) {
    echo $key . ' ' . $echo $value['name'];
}

答案 1 :(得分:1)

您也可以尝试自己获取密钥:

array_keys($yourEncodedJson);

这将返回提供的数组中的所有键名。

这样,您就不需要遍历它们了。

相关问题