News新闻

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

您的位置:首页      网络营销      PHP迭代与递归实现无限级分类

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

无限级分类是开发中常见的情况,因此本文对常见的无限极分类算法进行总结归纳.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=['i

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

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));
    我要评论
    共有 人参与,评论 条,顶帖 [点击查看]
  • 验证码:
  • 所有评论仅代表网友意见,与本站立场无关!