既然是查找当前分类下的所有子分类,那么就是根据当前分类的id,去找所有pid等于当前的分类,然后通过递归不断的去找下一级
上代码:
//执行函数
public function getchildren(){
//取出所有分类
$data=M('ushop_class')->select();
$res= $this->_getchildren($data,78);
dump($res);
}
//递归数据
public function _getchildren($data,$catid){
static $res=array();
foreach($data as $k=>$v){
//判断该条数据的pid 是否等于当前 id
if($v['pid']==$catid){
//将该条数据保存在静态变量中
$res[]=$v['name'];
//继续将查询出的数据中id代入递归中继续操作
$this->_getchildren($data,$v['id']);
}
}
return $res;
}
以上代码虽然能实现功能但是还是有个小bug 的
因为在static $res=array();是静态变量,所以在执行完一次后,结果将会保存在 $res中。当你在通过ajax不刷新的方式去查询的话,得到的结果就会包含上一次的数据所以做出以下改进
//执行函数
public function getchildren(){
//取出所有分类
$data=M('ushop_class')->select();
//每次执行前将$extis设为true 函数就会清空$res
$res= $this->_getchildren($data,78,true);
dump($res);
}
//递归数据
//$extis = false
public function _getchildren($data,$catid,$extis=false){
if($extis){
$res=[];
}
static $res=array();
foreach($data as $k=>$v){
//判断该条数据的pid 是否等于当前 id
if($v['pid']==$catid){
//将该条数据保存在静态变量中
$res[]=$v['name'];
//继续将查询出的数据中id代入递归中继续操作
$this->_getchildren($data,$v['id']);
}
}
return $res;
}
这下应该就没问题了,还请大神指点*_*