题有问题暂且不说,说一下解题思路,未总结成方法

<?php
$dir = [
    '0'=>['','主目录'],
    '1'=>['0','第一级目录1'],
    '2'=>['0','第一级目录2'],
    '3'=>['0','第一级目录3'],
    '4'=>['','主目录2'],
    '5'=>['1','第二级目录1'],
    ];
  
foreach($dir as $k => &$v){
    $v['id']= $k;
    $v['pid'] = $v[0];
    $v['title'] = $v[1];
    unset($dir[$k][0],$dir[$k][1]);
}

echo '<pre>';
print_r($dir);
echo '</pre>';

#递归方法实现无限极分类
function getTree($list,$pid=0,$level=0) {
  static $tree = array();
  foreach($list as $row) {
      if($row['pid'] !== ''){
    		if($row['pid']==$pid) {
        		$row['level'] = $level;
        		$tree[] = $row;
        		getTree($list, $row['id'], $level + 1);
        	}
      }elseif($row['pid'] === '' && $level == 0){
          $tree[] = $row;
      }
  }
  return $tree;
}

$dir = getTree($dir);

echo '<pre>';
print_r($dir);
echo '</pre>';

foreach($dir as $kk => $vv){
    if($vv['level'] !== NULL){
        $rs[] = str_repeat('--',$vv['level']+1).$vv['title'];
    }else{
        $rs[] = $vv['title'];
    }
}

echo '<pre>';
print_r($rs);
echo '</pre>';

结果是:

Array
(
    [0] => Array
        (
            [id] => 0
            [pid] => 
            [title] => 主目录
        )

    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => 第一级目录1
        )

    [2] => Array
        (
            [id] => 2
            [pid] => 0
            [title] => 第一级目录2
        )

    [3] => Array
        (
            [id] => 3
            [pid] => 0
            [title] => 第一级目录3
        )

    [4] => Array
        (
            [id] => 4
            [pid] => 
            [title] => 主目录2
        )

    [5] => Array
        (
            [id] => 5
            [pid] => 1
            [title] => 第二级目录1
        )

)
Array
(
    [0] => Array
        (
            [id] => 0
            [pid] => 
            [title] => 主目录
        )

    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => 第一级目录1
            [level] => 0
        )

    [2] => Array
        (
            [id] => 5
            [pid] => 1
            [title] => 第二级目录1
            [level] => 1
        )

    [3] => Array
        (
            [id] => 2
            [pid] => 0
            [title] => 第一级目录2
            [level] => 0
        )

    [4] => Array
        (
            [id] => 3
            [pid] => 0
            [title] => 第一级目录3
            [level] => 0
        )

    [5] => Array
        (
            [id] => 4
            [pid] => 
            [title] => 主目录2
        )

)
Array
(
    [0] => 主目录
    [1] => --第一级目录1
    [2] => ----第二级目录1
    [3] => --第一级目录2
    [4] => --第一级目录3
    [5] => 主目录2

难点在于相较于一般的无限级分类,多了一级 pid == ‘’ ,这一级单独判断。

发表评论

电子邮件地址不会被公开。 必填项已用*标注