【发布时间】:2021-05-31 10:48:16
【问题描述】:
我需要循环遍历 PHP 中的嵌套 JSON 数组。 JSON 键并不总是相同的,请参见下面的示例:
[
{
"id": 1,
"more": {
"city": "New York",
"street": "W 58th St"
},
"group": 4,
"name": "Ellie",
"status": "offline",
"phone": "1234567890",
"disabled": false
},
{
"id": 2,
"more": {
"city": "New York",
"street": "W 101st St",
"postal code": "12345"
},
"group": 7,
"name": "Diane",
"age": "25",
"phone": "",
"contact": "2",
}
]
到目前为止我的代码是这样的:
$user_details = json_decode($json, true);
foreach ($user_details as $details) {
foreach ($details as $key => $value) {
echo $key .': '. $value, PHP_EOL;
}
}
问题是,当我尝试运行上面的代码时,more 数组出现错误:
id: 1
<b>Warning</b>: Array to string conversion in <b>[...][...]</b> on line <b>15</b><br />
more: Array
group: 4
name: Ellie
status: offline
...
理想情况下,输出应该是这样的:
id: 1
city: New York
street: "W 58th St
group: 4
name: Ellie
status: offline
...
关于如何改进我的代码以输出正确数据的任何建议?
【问题讨论】:
标签: php arrays json multidimensional-array