PHP把从数据库查出的数据,根据主键外键,变成关系树(多叉树),从而转成json给前端使用。【递归思想,原创】

$arr = [
['id' => 3, 'pid' => 0, 'name' => 'A'],
['id' => 4, 'pid' => 3, 'name' => 'B'],
['id' => 5, 'pid' => 3, 'name' => 'C'],
['id' => 6, 'pid' => 3, 'name' => 'D'],
['id' => 7, 'pid' => 5, 'name' => 'E'],
['id' => 8, 'pid' => 4, 'name' => 'F'],
['id' => 9, 'pid' => 6, 'name' => 'G'],
['id' => 10, 'pid' => 0, 'name' => 'H'],
['id' => 11, 'pid' => 9, 'name' => 'I'],
['id' => 12, 'pid' => 8, 'name' => 'J'],
['id' => 13, 'pid' => 6, 'name' => 'K'],
['id' => 14, 'pid' => 10, 'name' => 'L'],
['id' => 15, 'pid' => 0, 'name' => 'M'],
['id' => 16, 'pid' => 4, 'name' => 'N'],
];


/**
* @param $arr 传入的数组
* @param $pid 连接关系参照字段
* @param $pKey 最终生成关系组的下标
* @param $tree 返回最终的处理结果
* @return array
*/
function ToTree($arr,$pid,$pKey,&$tree){
$currentDeep = [];
foreach($arr as $key => $value){
if($value['pid'] == $pid) { # 有儿子
$value[$pKey] = ToTree($arr,$value['id'],$pKey,$tree); # 找儿子
$currentDeep[] = $value;
}
}
if($currentDeep && $pid == 0){ # 当前根节点的儿子都找完了, 把当前根节点的儿子全部归位
$tree = $currentDeep;
}
return $currentDeep;
}

$tree = [];
ToTree($arr,0,'child',$tree);
#echo json_encode($tree);
print_r($tree);

原文地址:https://www.cnblogs.com/wangshuazi/p/14582678.html