/* 迭代和递归实现获取级联的数据(4种) */
$area = array(
array('id' => 1, 'name' => '0-1', 'parent' => 0),
array('id' => 2, 'name' => '0-2', 'parent' => 0),
array('id' => 3, 'name' => '0-3', 'parent' => 0),
array('id' => 4, 'name' => '0-1-4', 'parent' => 1),
array('id' => 5, 'name' => '0-2-5', 'parent' => 2),
array('id' => 6, 'name' => '0-2-6', 'parent' => 2),
array('id' => 7, 'name' => '0-3-7', 'parent' => 3),
array('id' => 8, 'name' => '0-3-8', 'parent' => 3),
array('id' => 9, 'name' => '0-1-4-9', 'parent' => 4),
array('id' => 10, 'name' => '0-1-4-10', 'parent' => 4),
array('id' => 11, 'name' => '0-2-5-11', 'parent' => 5),
array('id' => 12, 'name' => '0-3-8-12', 'parent' => 8),
array('id' => 14, 'name' => '0-2-5-11-14', 'parent' => 11),
array('id' => 15, 'name' => '0-2-5-11-15', 'parent' => 11)
);
/*
array(
array(
'id' => '',
'name' => ''
),
......
)
*/
function subTree($arr, $parent = 0)
{
$task = array($parent);
$tree = array();
while (! empty($task))
{
$flag = false;
foreach ($arr as $k => $a)
{
if ($a['parent'] == $parent)
{
$tree[] = $a;
array_push($task, $a['id']);
$parent = $a['id'];
unset($arr[$k]);
$flag = true;
}
}
if ($flag == false)
{
array_pop($task);
$parent = end($task);
}
}
return $tree;
}
function tree($arr, $id)
{
$tree = array();
while ($id != 0)
{
foreach ($arr as $a)
{
if ($a['id'] == $id)
{
$tree[] = $a;
$id = $a['parent'];
break;
}
}
}
return $tree;
}
function treeByR($arr, $id, $key = 0)
{
$tree = array();
if ($id != 0)
{
foreach ($arr as $k => $a)
{
if ($a['id'] == $id)
{
$tree[$key] = $a;
$key++;
unset($arr[$k]);
$tree = array_merge($tree, treeByR($arr, $a['parent'], $key));
return $tree;
}
}
}
return array();
}
/*
array (
id => '',
children = array(
id => '',
children = array(
)
)
......
)
*/
function levelSubTree($arr, $parent = 0)
{
$tree = array();
foreach ($arr as $a)
{
if ($a['parent'] == $parent)
{
$tree[$a['id']]['name'] = $a['name'];
$tree[$a['id']]['children'] = levelSubTree
($arr, $a['id']);
}
}
return $tree;
}