我有一些json,其中描述可以充当json数组的键。
例如:
{ 'groups' : array[
0 => {
'id' : '1'
'free gifts' : array[
0 => {'id': 1
'gift cards': array[
{..more json}
]
},
1 => { ... more json }
]
],
1 => {
'id' : '2'
'discounts & incentives' : array[
0 => { .. more json },
2 => { ... more json }
]
]
}
这可以继续任何深度,json的每个组或数组都有一个id值和一个名称或描述(属性名称)我想要的是递归迭代而不知道深度并得到:
(All) groups->id and descriptions so (1 = freegifts, 2 = discounts & incentives
和名称或描述为数组的所有其他级别相同
答案 0 :(得分:0)
首先,我将json转换为关联数组,然后使用以下递归函数迭代每个级别:
$array = json_decode($json);
recursive_key_val_lookup($array);
function recursive_key_val_lookup($array=[])
{
foreach($array as $key=>$val)
{
if(is_array($val))
{
echo "$key is array<br>";
$this->recursive_key_val_lookup($val);
} else {
echo "$key => $val";
}
}
}