自己写的PHP递归操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/licanfeng1/article/details/79363097
<?php
//导航栏分类
class Category{
	//组合一维数组
static public function unlimitedForLevel($cate,$html='--',$pid=0,$level=0){
	//echo 1;
	$arr=array();
	foreach ($cate as $v){
		if ($v['pid']==$pid){
			//根据level来输出$html的个数
			$v['level']=$level+1;
			$v['html']=str_repeat($html, $level);
			$arr[]=$v;
			
			//递归合并
			$arr=array_merge($arr,self::unlimitedForLevel($cate,$html,$v['id'],$level+1));
			
		} 
		
	}
	return $arr;
	
}
//无限级二(多维数组)
static public function unlimitedForLayer($cate,$name='child',$pid=0){
	$arr=array();
	foreach ($cate as $v){
		if($v['pid']==$pid){
			//$v['child']=self::unlimitedForLayer($cate,$v['id']);
			$v[$name]=self::unlimitedForLayer($cate,$name,$v['id']);
			$arr[]=$v;
			
		}
		
	}
	return $arr;
}
//可以根据子级id 返回所有的父级id
static public function getParents($cate,$id){
	$arr=array();
	foreach ($cate as $v){
		if($v['id']==$id){
			$arr[]=$v;
			$arr=array_merge(self::getParents($cate,$v['pid']),$arr);
	  }
		
	}
	//php>>字符串》》字符串处理函数》》substr()
	/*foreach ($cate as $v){
		$v['name'].">>"
		
	}*/
	return $arr;
	
}

//传递一个父级id,返回所有子级分类id(只返回id)
static  public function getChildsId($cate,$pid){
	$arr=array();
	foreach ($cate as $v){
		if($v['pid']==$pid){
			$arr[]=$v['id'];
			$arr=array_merge($arr,self::getChildsId($cate, $v['id']));
			
		}
		
	}
	return $arr;
}
//跟第四种一样,但是返回数组
static  public function getChilds($cate,$pid){
	$arr=array();
	foreach ($cate as $v){
		if($v['pid']==$pid){
			$arr[]=$v;
			$arr=array_merge($arr,self::getChilds($cate, $v['id']));
			
		}
		
	}
	return $arr;
}
}

?>

猜你喜欢

转载自blog.csdn.net/licanfeng1/article/details/79363097