php迭代和递归求子地区无限级分类数组

<?php
$area = array(
array('id'=>1,'name'=>'安徽','parent'=>0),
array('id'=>2,'name'=>'海淀','parent'=>7),
array('id'=>3,'name'=>'濉溪县','parent'=>5),
array('id'=>4,'name'=>'昌平','parent'=>7),
array('id'=>5,'name'=>'淮北','parent'=>1),
array('id'=>6,'name'=>'朝阳','parent'=>7),
array('id'=>7,'name'=>'北京','parent'=>0),
array('id'=>8,'name'=>'上地','parent'=>2)
);

//打印子地区
function findson($area,$id=0){
	$row=array();
   foreach($area as $v){
      if($v['parent']==$id){
	     $row[]=$v;
	  }
   }
   return $row;
}

//print_r(findson($area,7));//打印id为7(北京)的子地区数组

echo '<hr>';

//打印子孙树(递归)
function findzisun1($area,$id=0,$level=0){
   static  $row=array();//用静态递归时就不会被重写赋值为空数组了
	 foreach($area as $v){
      if($v['parent']==$id){
		  $v['level']=$level;
	     $row[]=$v;
		 
		findzisun1($area,$v['id'],$level+1);
	  }
   }
   return $row;
}

//print_r(findzisun1($area));//打印id为0(整个地区)的子孙数组


//打印子孙树(迭代)

function findzisun2($area,$id=0){
  $renwu=array($id);//任务数组
  $row=array();
  while(!empty($renwu)){
	  $sign=false;//有查到子地区就为true,判断是否弹出任务数组中的那个没查到子地区的id数

  foreach($area as $key=>$v){
    if($v['parent']==$id){
	  $row[]=$v;//记录子地区到数组中区
	  $id=$v['id'];//将子地区的id作为下次要查的地区parent
	  array_push($renwu,$id);//将查到的id记录到任务数组0,1,5,3
	  unset($area[$key]);//删除查到的那条记录
	  $sign=true;//有子地区查到就将标示符设为true,就不会执行下面的弹出,
	}
  }
  if($sign==false){//因为id为3的地区没找到子地区,,sign为false,此时wenwu为0,1,5,3,弹出最后一个最后元素3,
    array_pop($renwu);
	$id=end($renwu);//id=5,id=1执行上面foreach都没有字地区,直到id=0又有了子地区
  }

  print_r($renwu);
  /*
Array
(
    [0] => 0
    [1] => 1
    [2] => 5
)
Array
(
    [0] => 0
    [1] => 1
    [2] => 5
    [3] => 3
)
Array
(
    [0] => 0
    [1] => 1
    [2] => 5
)
Array
(
    [0] => 0
    [1] => 1
)
Array
(
    [0] => 0
)
Array
(
    [0] => 0
    [1] => 7
)
Array
(
    [0] => 0
    [1] => 7
    [2] => 2
    [3] => 8
)
Array
(
    [0] => 0
    [1] => 7
    [2] => 2
)
Array
(
    [0] => 0
    [1] => 7
)
Array
(
    [0] => 0
    [1] => 7
    [2] => 4
)
Array
(
    [0] => 0
    [1] => 7
)
Array
(
    [0] => 0
    [1] => 7
    [2] => 6
)
Array
(
    [0] => 0
    [1] => 7
)
Array
(
    [0] => 0
)
Array
(
)
  */
 }

  return $row;


}
//print_r(findzisun2($area,0));


?>

你可能感兴趣的:(PHP,地区,无限级分类)