原始数据
$son_parent = [
1 => 0,
2 => 0,
11 => 1,
12 => 1,
21 => 2,
22 => 2,
111 => 11,
];
递归
function recursionTree($tree, $root = null) {
$return = array();
# Traverse the tree and search for direct children of the root
foreach($tree as $child => $parent) {
# A direct child is found
if($parent == $root) {
# Remove item from tree (we don't need to traverse this again)
unset($tree[$child]);
# Append the child into result array and parse its children
$return[] = array(
'name' => $child,
'children' => recursionTree($tree, $child)
);
}
}
return empty($return) ? null : $return;
}
print_r(recursionTree($son_parent, 0));
/*
Array
(
[0] => Array
(
[name] => 1
[children] => Array
(
[0] => Array
(
[name] => 11
[children] => Array
(
[0] => Array
(
[name] => 111
[children] =>
)
)
)
[1] => Array
(
[name] => 12
[children] =>
)
)
)
[1] => Array
(
[name] => 2
[children] => Array
(
[0] => Array
(
[name] => 21
[children] =>
)
[1] => Array
(
[name] => 22
[children] =>
)
)
)
)
*/
传引用
//父子级
function quote_tree($array){
$flat = array();
$tree = array();
foreach ($array as $child => $parent) {
if (!isset($flat[$child])) {
$flat[$child] = array();
}
if (!empty($parent)) {
$flat[$parent][$child] =& $flat[$child];
} else {
$tree[$child] =& $flat[$child];
}
}
return $tree;
}
//子父级
function quote_tree2($array){
$flat = array();
$tree = array();
foreach ($array as $child => $parent) {
if (!isset($flat[$child])) {
$flat[$child] = array();
}
if (!empty($parent)) {
$flat[$child][$parent] =& $flat[$parent];
} else {
$flat[$child] = 0;
}
}
return $flat;
}
print_r(quote_tree($son_parent));
/*
Array
(
[1] => Array
(
[11] => Array
(
[111] => Array
(
)
)
[12] => Array
(
)
)
[2] => Array
(
[21] => Array
(
)
[22] => Array
(
)
)
)
*/
print_r(quote_tree2($son_parent));
/*
Array
(
[1] => 0
[2] => 0
[11] => Array
(
[1] => 0
)
[12] => Array
(
[1] => 0
)
[21] => Array
(
[2] => 0
)
[22] => Array
(
[2] => 0
)
[111] => Array
(
[11] => Array
(
[1] => 0
)
)
)
*/