无限级分类 递归和迭代

header('content-type:text/html;charset=utf-8');
 $list=Array (  Array ( 'id' => 1 ,'name' => 'A' ,'pid' => 0 ) , Array ( 'id' => 2 ,'name' => 'B' ,'pid' => 0 ) , Array ( 'id' => 3 ,'name' => 'C' ,'pid' => 1 ), Array ( 'id' => 4 ,'name' => 'D' ,'pid' => 1 ) , Array ( 'id' => 5 ,'name' => 'E' ,'pid' => 2 ) , Array ( 'id' => 6 ,'name' => 'F' ,'pid' => 2 ) , Array ( 'id' => 7 ,'name' => 'G' ,'pid' => 3 ) , Array ( 'id' => 8 ,'name' => 'H' ,'pid' => 3 ) , Array ( 'id' => 9 ,'name' => 'I' ,'pid' => 3 ) , Array ( 'id' => 10 ,'name' => 'J' ,'pid' => 4 ) , Array ( 'id' => 11 ,'name' => 'K' ,'pid' => 4 ), Array ( 'id' => 12 ,'name' => 'L' ,'pid' => 4 ) , Array ( 'id' => 13 ,'name' => 'M' ,'pid' => 5 ) , Array ( 'id' => 14 ,'name' => 'N' ,'pid' => 5 ) , Array ( 'id' => 15 ,'name' => 'O' ,'pid' => 5 ) , Array ( 'id' => 16 ,'name' => 'P' ,'pid' => 6 ) , Array ( 'id' => 17 ,'name' => 'Q' ,'pid' => 6 ) , Array ( 'id' => 18 ,'name' => 'R' ,'pid' => 6 ) , Array ( 'id' => 19 ,'name' => 'S' ,'pid' => 6 ) , Array ( 'id' => 20 ,'name' => 'T' ,'pid' => 0 ) , Array ( 'id' => 21 ,'name' => 'U' ,'pid' => 20 ) , Array ( 'id' => 22 ,'name' => 'V' ,'pid' => 20 ) , Array ( 'id' => 23 ,'name' => 'W' ,'pid' => 21 ) , Array ( 'id' => 24 ,'name' => 'X' ,'pid' => 21 ) , Array ( 'id' => 25 ,'name' => 'Y' ,'pid' => 22 ) , Array ( 'id' => 26 ,'name' => 'Z' ,'pid' => 22 ) );
echo "递归
";
 function getTree($list,$parent,$level=0)
 {
     $tree=array();
    foreach ($list as  $value) {
        if ($value['pid']==$parent) {
            $value['level']=$level;
            $tree[]=$value;
            $tree=array_merge($tree,getTree($list,$value['id'],$level+1));
        }
    }
     return $tree;
 }
$data=getTree($list,0);
foreach ($data as $key => $value) {
    echo str_repeat("——",$value['level']),$value['name'],'
';
}
echo "
","迭代";

function iterate($list,$parent)
{
    $tree=array();
    while ($parent>0) {
        foreach ($list as $key => $value) {
            if ($value['id']==$parent) {
                $tree[]=$value;
                $parent=$value['pid'];
                break;
            }
        }
        
    }
    return $tree;
}

var_dump(iterate($list,26));

echo "


引用赋值
";

function tree($list)
{
    $tree = array();
    //第一步,将所有的分类id作为数组key,并创建children单元
    foreach($list as $value){
        $tree[$value['id']] = $value;
        $tree[$value['id']]['children'] = array();
    }
    //第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。
    foreach ($tree as $key=>$value) {
        if ($value['pid'] != 0) {
            $tree[$value['pid']]['children'][] = &$tree[$key];
        }
    }
    return $tree;
}
$data=tree($list);
print_r($data);

 ?>

你可能感兴趣的:(php)