关于多维数组降维、深度和获取父键的问题
程序员文章站
2023-12-27 16:00:15
...
我有一个数组,结构是这样的:
也有可能是这样的结构:
也就是说层数、顺序都不是固定的。
我想把他降为一维数组,并记录下每一个一维数组的深度,对应的父键等
以下是第二个数组期望得到的结果:
想了一晚上了。。。请大神帮帮忙
啊!!!!
十分感谢!
这一步我实在想不出来。
$json = '[{"id":27,"children":[{"id":28,"children":[{"id":30},{"id":29}]}]},{"id":31},{"id":32}]';$arry = json_decode($json,true);
也有可能是这样的结构:
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);
也就是说层数、顺序都不是固定的。
我想把他降为一维数组,并记录下每一个一维数组的深度,对应的父键等
以下是第二个数组期望得到的结果:
Array ([0] => Array ( [id] => 27 [level] => 0 [parent] => 0 )[1] => Array ( [id] => 30 [level] => 1 [parent] => 27 )[2] => Array ( [id] => 31 [level] => 2 [parent] => 30 )[3] => Array ( [id] => 28 [level] => 0 [parent] => 0 )[4] => Array ( [id] => 29 [level] => 1 [parent] => 28 )[5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ) )
想了一晚上了。。。请大神帮帮忙
回复讨论(解决方案)
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);print_r(foo($arry));function foo($ar, $level=0, $parent=0, &$res=array()) { foreach($ar as $v) { $t = array(); $v['level'] = $level; $v['parent'] = $parent; if(isset($v['children'])) { $t = $v['children']; unset($v['children']); } $res[] = $v; if($t) foo($t, $level+1, $v['id'], $res); } return $res;}
Array( [0] => Array ( [id] => 27 [level] => 0 [parent] => 0 ) [1] => Array ( [id] => 30 [level] => 1 [parent] => 27 ) [2] => Array ( [id] => 31 [level] => 2 [parent] => 30 ) [3] => Array ( [id] => 28 [level] => 0 [parent] => 0 ) [4] => Array ( [id] => 29 [level] => 1 [parent] => 28 ) [5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ))
$json = '[{"id":27,"children":[{"id":30,"children":[{"id":31}]}]},{"id":28,"children":[{"id":29}]},{"id":32}]';$arry = json_decode($json,true);print_r(foo($arry));function foo($ar, $level=0, $parent=0, &$res=array()) { foreach($ar as $v) { $t = array(); $v['level'] = $level; $v['parent'] = $parent; if(isset($v['children'])) { $t = $v['children']; unset($v['children']); } $res[] = $v; if($t) foo($t, $level+1, $v['id'], $res); } return $res;}
Array( [0] => Array ( [id] => 27 [level] => 0 [parent] => 0 ) [1] => Array ( [id] => 30 [level] => 1 [parent] => 27 ) [2] => Array ( [id] => 31 [level] => 2 [parent] => 30 ) [3] => Array ( [id] => 28 [level] => 0 [parent] => 0 ) [4] => Array ( [id] => 29 [level] => 1 [parent] => 28 ) [5] => Array ( [id] => 32 [level] => 0 [parent] => 0 ))
啊!!!!
十分感谢!
if(isset($v['children'])) { $t = $v['children']; unset($v['children']); }
这一步我实在想不出来。
推荐阅读