看到你,梁松远的博客

位置 » 主页 » 代码分享 » 分享一段快速无限下级分类归类的代码

分享一段快速无限下级分类归类的代码

 


function getTreeNew(){
$tmp = [];
foreach($this->categories as $node){
$tmp[$node->{$this->parent_name}][] = $node;
}
krsort($tmp);
foreach($tmp as $pid => &$childs){
foreach($childs as &$child){
if(isset($tmp[$child->{$this->id_name}])){
$child->child = $tmp[$child->{$this->id_name}];
}
}
}

return $tmp[0];
} 上面的是object,下面的这个是数组形式的
function getTreeChild(){
$tmp = [];
foreach($this->categories as $node){
$tmp[$node[$this->parent_name]][] = $node;
}
krsort($tmp);
foreach($tmp as $pid => &$childs){
foreach($childs as &$child){
if(isset($tmp[$child[$this->id_name]])){
$child['child'] = $tmp[$child[$this->id_name]];
}
}
}

return $tmp[0];
} 上面都是需要用在类里的,下面这个可以单独使用。
function getTreeNew($categories, $id_name = 'id', $parent_name = 'fid'){
$tmp = [];
foreach($categories as $node){
$tmp[$node[$parent_name]][] = $node;
}
krsort($tmp);
foreach($tmp as $pid => &$childs){
foreach($childs as &$child){
if(isset($tmp[$child[$id_name]])){
$child['child'] = $tmp[$child[$id_name]];
}
}
}

return $tmp[0];
}