<?php
$nodesArrays = [
[‘id‘ => 1, ‘pid‘ => 0, ‘name‘ => ‘a‘],
[‘id‘ => 2, ‘pid‘ => 0, ‘name‘ => ‘b‘],
[‘id‘ => 3, ‘pid‘ => 1, ‘name‘ => ‘c‘],
[‘id‘ => 4, ‘pid‘ => 2, ‘name‘ => ‘d‘],
[‘id‘ => 5, ‘pid‘ => 6, ‘name‘ => ‘e‘],
[‘id‘ => 6, ‘pid‘ => 4, ‘name‘ => ‘f‘],
[‘id‘ => 7, ‘pid‘ => 6, ‘name‘ => ‘g‘],
[‘id‘ => 8, ‘pid‘ => 6, ‘name‘ => ‘h‘],
[‘id‘ => 9, ‘pid‘ => 10, ‘name‘ => ‘i‘],
[‘id‘ => 10, ‘pid‘ => 8, ‘name‘ => ‘j‘],
[‘id‘ => 12, ‘pid‘ => 6, ‘name‘ => ‘l‘],
[‘id‘ => 15, ‘pid‘ => 7, ‘name‘ => ‘m‘],
];
$nodesArray1 = [
[‘id‘ => 1, ‘pid‘ => 4, ‘name‘ => ‘a‘],
[‘id‘ => 2, ‘pid‘ => 0, ‘name‘ => ‘b‘],
[‘id‘ => 3, ‘pid‘ => 1, ‘name‘ => ‘c‘],
[‘id‘ => 4, ‘pid‘ => 2, ‘name‘ => ‘d‘],
[‘id‘ => 5, ‘pid‘ => 6, ‘name‘ => ‘e‘],
[‘id‘ => 6, ‘pid‘ => 4, ‘name‘ => ‘f‘],
[‘id‘ => 7, ‘pid‘ => 6, ‘name‘ => ‘g‘],
[‘id‘ => 8, ‘pid‘ => 6, ‘name‘ => ‘h‘],
[‘id‘ => 9, ‘pid‘ => 10, ‘name‘ => ‘i‘],
[‘id‘ => 10, ‘pid‘ => 8, ‘name‘ => ‘j‘],
[‘id‘ => 12, ‘pid‘ => 6, ‘name‘ => ‘l‘],
[‘id‘ => 15, ‘pid‘ => 7, ‘name‘ => ‘m‘],
];
//换个思路 ,不改变源数据,新创建一个根节点,一个子节点树
function getTreeNode3($list, $root = 0, $pk=‘id‘, $pid = ‘pid‘, $child = ‘_child‘) {
// 创建根节点
$root_tree = array();
// 创建子节点
$node_tree = array();
// 迷路节点
$no_tree = array();
if(is_array($list)) {
//既然不能使用数组函数改变源数据的下标,那么就把子节点的下标放在子节点tree即可
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
$nowId = $data[$pk];
//根据$root 值 确定根节点数组,非 0 root 有问题
if ($root == $parentId && $root == 0) {
$node_tree[$nowId] = $data;
$root_tree[$nowId] = &$node_tree[$nowId];
}else if ($root == $nowId && $root != 0) {
$node_tree[$nowId] = $data;
$root_tree[$nowId] = &$node_tree[$nowId];
if(isset($no_tree[$nowId])) {
$node_tree[$nowId][$child] = &$no_tree[$nowId];
}
}else {
//同时确认 根节点 与 子节点是否都存在
//先找子节点
//$flag_node_tree = false;
//同时存在根节点,则映射父节点 与 子节点关联
if (isset($root_tree[$parentId]) && isset($node_tree[$parentId])) {
//同时存在 映射父子关系,改变子
$root_tree[$parentId] = &$node_tree[$parentId];
$node_tree[$nowId] = $data;
$node_tree[$parentId][$child][$nowId] = &$node_tree[$nowId];
if(isset($no_tree[$nowId])) {
$node_tree[$nowId][$child] = &$no_tree[$nowId];
}
}else if (!isset($root_tree[$parentId]) && isset($node_tree[$parentId])) {
//父不存在子存在则写入子的子
$node_tree[$nowId] = $data;
$node_tree[$parentId][$child][$nowId] = &$node_tree[$nowId];
if(isset($no_tree[$nowId])) {
$node_tree[$nowId][$child] = &$no_tree[$nowId];
}
}else if (isset($root_tree[$parentId]) && !isset($node_tree[$parentId])) {
//父节点存在,而子节点没有
$node_tree[$nowId] = $data;
$root_tree[$parentId][$child][$nowId] = &$node_tree[$nowId];
if(isset($no_tree[$nowId])) {
$root_tree[$parentId][$child] = &$no_tree[$nowId];
}
}else {
$node_tree[$nowId] = $data;
$no_tree[$parentId][$nowId] = &$node_tree[$nowId];
}
}
/*echo "\nroot_tree\n";
print_r($root_tree);
echo "\nnode_tree\n";
print_r($node_tree);
echo "\nno_tree\n";
print_r($no_tree);*/
}
}
return $root_tree;
}
$treeval = getTreeNode3($nodesArrays,8);
print_r($treeval);
原文地址:http://blog.51cto.com/nightwizard/2103540