我有这个JSON字符串:
$json= '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}'
我想从json中检索所有值和键,输出应该如下:
id: 123
name: john smith
gender: MALE
phone:
number: +919999999999
numberType: MOBILE
我已经尝试过这段代码,但无法获得手机输出:
$jsond = json_decode($json);
foreach($jsond->data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
}
}
答案 0 :(得分:1)
这正是array_walk_recursive
的用途:
<?php
$json = '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}';
$jsond = json_decode($json,true);
function test_print($val, $key)
{
echo "$key : $val<br/>\n";
}
array_walk_recursive($jsond, 'test_print');
导致此输出:
id : 123<br/>
name : john smith<br/>
gender : MALE<br/>
number : +919999999999<br/>
numberType : MOBILE<br/>
&#13;