1. 程式人生 > >輕松遞歸無限分類

輕松遞歸無限分類

類集 子類 span [1] each ray 兩個 _array 無限

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

輕松遞歸無限分類