**将一个平面的二维数组按照指定的字段转换为树状结构**
**代码:**
~~~
function toTree($arr, $key_node_id, $key_parent_id = 'parent_id', $key_childrens = 'children', $treeIndex = false, & $refs = null) {
$refs = array ();
foreach ( $arr as $offset => $row ) {
$arr [$offset] [$key_childrens] = array ();
$refs [$row [$key_node_id]] = & $arr [$offset];
}
$tree = array ();
foreach ( $arr as $offset => $row ) {
$parent_id = $row [$key_parent_id];
if ($parent_id) {
if (! isset ( $refs [$parent_id] )) {
if ($treeIndex) {
$tree [$offset] = & $arr [$offset];
} else {
$tree [] = & $arr [$offset];
}
continue;
}
$parent = & $refs [$parent_id];
if ($treeIndex) {
$parent [$key_childrens] [$offset] = & $arr [$offset];
} else {
$parent [$key_childrens] [] = & $arr [$offset];
}
} else {
if ($treeIndex) {
$tree [$offset] = & $arr [$offset];
} else {
$tree [] = & $arr [$offset];
}
}
}
return $tree;
}
~~~
**调用:**
~~~
$rows = array(
array('id' => 1, 'value' => '1-1', 'parent' => 0),
array('id' => 2, 'value' => '2-1', 'parent' => 0),
array('id' => 3, 'value' => '3-1', 'parent' => 0),
array('id' => 7, 'value' => '2-1-1', 'parent' => 2),
array('id' => 8, 'value' => '2-1-2', 'parent' => 2),
array('id' => 9, 'value' => '3-1-1', 'parent' => 3),
array('id' => 10, 'value' => '3-1-1-1', 'parent' => 9),
);
$tree = Helper_Array::tree($rows, 'id', 'parent', 'nodes');
dump($tree);
//输出结果:
array(
array('id' => 1, ..., 'nodes' => array()),
array('id' => 2, ..., 'nodes' => array(
array(..., 'parent' => 2, 'nodes' => array()),
array(..., 'parent' => 2, 'nodes' => array()),
),
array('id' => 3, ..., 'nodes' => array(
array('id' => 9, ..., 'parent' => 3, 'nodes' => array(
array(..., , 'parent' => 9, 'nodes' => array(),
),
),
)
~~~