php解析对象层次结构和数组的JSON混合来读取值
需要从数组“places”读取值->然后从restapi接收的响应($response)读取数组“parents”的值:php解析对象层次结构和数组的JSON混合来读取值,php,arrays,json,rest,Php,Arrays,Json,Rest,需要从数组“places”读取值->然后从restapi接收的响应($response)读取数组“parents”的值: 然后使用$json=json\u decode($response,true)进行解码 Array ( [status_code] => 200 [data] => Array ( [places] => Array ( [0] =
然后使用
$json=json\u decode($response,true)进行解码代码>
Array
(
[status_code] => 200
[data] => Array
(
[places] => Array
(
[0] => Array
(
[id] => 11878
[name] => Times Square
[name_suffix] => Manhattan, New York City, USA
[parents] => Array
(
[0] => Array
(
[id] => 32280039
[name] => Theater District
[level] => neighbourhood
)
[1] => Array
(
[id] => poi:28010161
[name] => Manhattan Community Board 5
[level] => region
)
[2] => Array
(
[id] => region:1981637
[name] => Manhattan Island
[level] => island
)
[3] => Array
(
[id] => poi:28043160
[name] => Manhattan
[level] => neighbourhood
)
)
[perex] => Times Square (nicknamed “The Crossroads of the World”) is the best known square in New York City and also its beating heart.
)
[1] => Array
(
[id] => 11874
[name] => Empire State Building
[name_suffix] => Manhattan, New York City, USA
[parents] => Array
(
[0] => Array
(
[id] => poi:32108808
[name] => Midtown South
[level] => neighbourhood
)
[1] => Array
(
[id] => poi:28010161
[name] => Manhattan Community Board 5
[level] => region
)
[2] => Array
(
[id] => region:1981637
[name] => Manhattan Island
[level] => island
)
[3] => Array
(
[id] => region:46071
[name] => Manhattan
[level] => neighbourhood
)
)
[perex] => An iconic Art Deco skyscraper and one of the best known buildings in New York. It got its name from the city’s nickname the "Empire State".
)
)
)
)
我正在努力循环遍历对象,这些对象在请求时是未知的,并不总是相同的,也不适用于每个单独的请求
foreach ($json->data as $places_list) {
foreach ($places_list->places as $placesItem) {
foreach($placesItem->(HELP HERE) as $place_detail) {
echo json_encode($place_detail) . "\n";
}
}
}
您能否帮助实现一个通用函数,它允许(a)进入“位置”级别,然后(b)从“父级”检索值
谢谢:)您的代码与数据输出不匹配,因为它使用对象表示法。但无论如何,这只是获得正确的数据层次结构的问题
这段代码遍历了位置的列表
数组,echo就是其中的名称。然后一个内部循环遍历父元素
并从中输出名称
foreach ($json['data']['places'] as $places_list) {
echo $places_list['name']."-";
foreach ($places_list['parents'] as $parents) {
echo $parents['name'] ."/";
}
echo PHP_EOL;
}
哪个输出
Times Square-Theater District/Manhattan Community Board 5/Manhattan Island/Manhattan/
Empire State Building-Midtown South/Manhattan Community Board 5/Manhattan Island/Manhattan/
非常感谢。当然我错过了这个,用对象表示法..你的函数很漂亮,按预期工作。祝你圣诞快乐