我有一个多维数组(树视图),我正在尝试从中创建一个简单的数组。
树视图数组示例:
$arr = [
0 => [
'id' => 1,
'children' => [
0 => [
'id' => 2,
'children' => [
0 => [
'id' => 3
]
]
]
]
]
];
我想要的是获取一个数组作为键,父ID作为值的数组。
示例:
$arr = [
1 => 0,
2 => 1,
3 => 2
];
答案 0 :(得分:0)
与此同时,我解决了这个问题:
$result = [];
function recur($arr, $parent = 0) {
global $result;
foreach ($arr as $x ) {
$result[$x['id']] = $parent;
if (isset($x['children'])) {
recur($x['children'], $x['id']);
}
}
return 1;
}
recur($arr);
答案 1 :(得分:0)
function relation($parent, $child, &$result)
{
if($child['children']) {
$result[$child['id']] = $parent;
relation($child['id'], $child['children'], $result);
}else{
$result[$child['id']] = $parent;
}
}
$arr1 = array('id'=>3);
$arr2 = array('id'=>2, 'children'=>$arr1);
$arr3 = array('id'=>1, 'children' => $arr2);
$result = array();
relation(0, $arr3, $result);
var_dump($result);