首页 > 代码库 > 轻松递归无限分类

轻松递归无限分类

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)
  }
}
 
 
 

轻松递归无限分类