首页 > 代码库 > 轻松递归无限分类
轻松递归无限分类
protected $idName = ‘stc_id‘;
protected $parentName = ‘stc_parent_id‘;
/**
* 获取子集并递归
* @param $data
* @param $id
* @param array $new_arr
* @return array
*/
private function whileWhere($data,$id,&$new_arr=[])
{
$select_frist = $this->get_child_array($data,$id);
foreach ($select_frist as $Keies => $value) {
$new_obj = $this->get_child_array($data,$value[$this->idName]);
if(count($new_obj)){
$new_value = [];
$new_arr[] = array_merge($value,["node"=> $this->whileWhere($data,$value[$this->idName],$new_value[])]);
continue;
}
$new_arr[] = $value;
}
return $new_arr;
}
/**
* 子类集
* @param $data
* @param $id
* @return array
*/
protected function get_child_array($data,$id)
{
$new_data = [];
foreach ($data as $k=>$v){
if($v[$this->parentName] === $id){
$new_data[] = array_merge($data[$k],$this->is_child($data,$v[$this->idName]));
}
}
return $new_data;
}
/**
* 查询是否有子集
* @param $data
* @param $id
* @return array
*/
protected function is_child($data,$id)
{
foreach ($data as $k=>$v){
if($id === $v[$this->parentName] ){
return [‘child‘=>true];
}
}
return [‘child‘=>false];
}
请不要使用数据库查询操作递归,用语言本身才不会被外部约束!
以上使用id 父id 两个字段完成递归,举一反三哟!
结果:
array(3) { [0] => array(7) { ["stc_id"] => int(1) ["stc_name"] => string(6) "灏忓崕" ["stc_parent_id"] => int(0) ["stc_state"] => int(1) ["stc_sort"] => int(1) ["child"] => bool(true) ["node"] => array(1) { [0] => array(7) { ["stc_id"] => int(3) ["stc_name"] => string(6) "灏忓洓" ["stc_parent_id"] => int(1) ["stc_state"] => int(0) ["stc_sort"] => int(0) ["child"] => bool(true) ["node"] => array(1) { [0] => array(6) { ["stc_id"] => int(4) ["stc_name"] => string(6) "灏忎簲" ["stc_parent_id"] => int(3) ["stc_state"] => int(0) ["stc_sort"] => int(0) ["child"] => bool(false) } } } } } [1] => array(6) { ["stc_id"] => int(5) ["stc_name"] => string(6) "灏忓叚" ["stc_parent_id"] => int(0) ["stc_state"] => int(0) ["stc_sort"] => int(0) ["child"] => bool(false) } [2] => array(6) { ["stc_id"] => int(2) ["stc_name"] => string(6) "灏忕櫧" ["stc_parent_id"] => int(0) ["stc_state"] => int(0) ["stc_sort"] => int(0) ["child"] => bool(false) } }
轻松递归无限分类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。