js版本
function toTree(data) {
let result = []
if (!Array.isArray(data)) {
return result
}
data.forEach(item => {
delete item.children;
});
let map = {};
data.forEach(item => {
map[item.id] = item;
});
data.forEach(item => {
let parent = map[item.pid];
if (parent) {
(parent.children || (parent.children = [])).push(item);
} else {
result.push(item);
}
});
return result;
}
php版本
public function commentSort($data ,$pid = 0, $ischild=false,$fatherindex=0)
{
static $arr = array() ;
foreach ($data as $key => $value) {
if($value['pid'] == $pid){
if($ischild){
//下面相当于
//array_push($arr[$fatherindex]['children'],$value) ;
static $child = array() ;
$child[$fatherindex][] = $value ;
$arr[$fatherindex]['children'] = $child[$fatherindex] ;
$fatherindex = $fatherindex;
} else {
$arr[$key] = $value ;
$arr[$key]['children'] = [] ;
$fatherindex = $key ;
}
//继续当前id的子类
self::commentSort($data,$value['id'],true,$fatherindex) ;
}
}
return (array)$arr;
}