無限極結構循環,不適用任何數組函數,一次循環,並根據給出的root 快速篩選
$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‘ => 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‘ => 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‘ => 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);
無限極結構循環,不適用任何數組函數,一次循環,並根據給出的root 快速篩選