[英]read json object in php
I have some json object like this: 我有一些像这样的json对象:
{"g_aaa77":
{"'title'":"title2",
"'r_a6cff'":
{"name":"name2","price":"2"},
"'r_7fc7b'":
{"name":"name22","price":"22"}
},
"g_a36b5":
{"title":"title1",
"r_4e122":
{"name":"name1","price":"1"},
"r_155fa":
{"name":"name11","price":"11"}
}
}
g_aaa77
and g_a36b5
are a random string. g_aaa77
和g_a36b5
是一个随机字符串。
Also r_a6cff
, r_7fc7b
, r_4e122
, r_155fa
还有
r_a6cff
, r_7fc7b
, r_4e122
, r_155fa
How can I read this json? 我怎么能读这个json?
Normally is this way: 通常是这样的:
$json = { .. };
$json->g_a36b5->title;
But I do not have 'g_a36b5'. 但我没有'g_a36b5'。 it is a random string.
它是一个随机字符串。
maybe I must convert this json to another or something like this. 也许我必须把这个json转换成另一个或类似的东西。
can u please tell me how can I read this json? 你能告诉我怎样才能读到这个json?
First of, json_decode
your json. 首先,
json_decode
你的json。
$array = json_decode($json, true);
Now you'll need to loop through with a foreach, since you still don't know what the keys are: 现在你需要使用foreach循环,因为你仍然不知道密钥是什么:
foreach($array AS $key => $subarray) {
echo $key . ": " . print_r($subarray, true);
}
If you don't care about keeping the keys, you can just remove those random strings with array_values
. 如果您不关心保留密钥,可以使用
array_values
删除那些随机字符串。
$array = array_values($array);
Now you can still loop through it, or just address an array element directly via numeric key: 现在你仍然可以遍历它,或者只是通过数字键直接寻址数组元素:
print_r($array[0]);
echo $array[1]['title']; // title1
Example: https://3v4l.org/s2it1 示例: https : //3v4l.org/s2it1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.