递归实现无限极分类

$arr = array(
    array('id' => 1,'pid' => 0, 'name' => '电脑'),
    array('id' => 2,'pid' => 0, 'name' => '家用电器'),
    array('id' => 3,'pid' => 2, 'name' => '大家电'),
    array('id' => 4,'pid' => 3, 'name' => '空调'),
    array('id' => 5,'pid' => 1, 'name' => '平板电脑'),
    array('id' => 6,'pid' => 1, 'name' => '台式电脑'),
    array('id' => 7,'pid' => 2, 'name' => '厨房电器'),
    array('id' => 8,'pid' => 7, 'name' => '电压锅'),
    array('id' => 9,'pid' => 7, 'name' => '微波炉'),
);

function showTree($arr, $pid = 0, $l = 0){
    static $newArr = [];
    foreach($arr as $v){
        if($v['pid'] == $pid){
            $v['level'] =$l+1;
            for($i=0; $i < $v['level'] - 1; ++$i){
                echo "----";
            }
            echo $v['name'],'
'
; $newArr[] = $v; //var_dump($v); showTree($arr,$v['id'],$v['level']); } } return $newArr; } showTree($arr);

你可能感兴趣的:(php)