News新闻

业界新闻动态、技术前沿
Who are we?

您的位置:首页      乐道系统FAQ      PHP迭代与递归实现无限级分类

PHP迭代与递归实现无限级分类

发布日期:2017-08-28 00:00:00 66

无限级分类是开发中常见的情况,因此本文对常见的无限极分类算法进行总结归纳.

1.循环迭代实现

$arr = [
  1=>['id'=>1,'name'=>'父1','father'=>NULL],
  2=>['id'=>2,'name'=>'父2','father'=>NULL],
  3=>['id'=>3,'name'=>'父3','father'=>NULL],
  4=>['id'=>4,'name'=>'儿1-1','father'=>1],
  5=>['id'=>5,'name'=>'儿1-2','father'=>1],
  6=>['id'=>6,'name'=>'儿1-3','father'=>1],
  7=>['id'=>7,'name'=>'儿2-1','father'=>2],
  8=>['id'=>8,'name'=>'儿2-1','father'=>2],
  9=>['id'=>9,'name'=>'儿3-1','father'=>3],
  10=>['id'=>10,'name'=>'儿3-1-1','father'=>9],
  11=>['id'=>11,'name'=>'儿1-1-1','father'=>4],
  12=>['id'=>12,'name'=>'儿2-1-1','father'=>7],
];
function generateTree($items){
  $tree = array();
  foreach($items as $item){
    if(isset($items[$item['father']])){
      $items[$item['father']]['son'][] = &$items[$item['id']]; 
    }else{
      $tree[] = &$items[$item['id']];
    }
  }
  return $tree;
}
$tree = generateTree($arr);
print_r(json_encode($tree));