PHP:在多层树形数组中查找指定键并获取所有子键(含自身)
)
需要实现一个功能:输入指定键,返回包含该键及其所有层级子键的一维数组。例如: - 查找键`7`时,返回:
Array
(
[0] => 7
[1] => 24
[2] => 38
[3] => 78
[4] => 103
[5] => 121
[6] => 163
[7] => 162
[8] => 213
[9] => 214
[10] => 215
...
)
- 查找键`163`时,返回:
Array
(
[0] => 163
[1] => 162
[2] => 213
[3] => 214
[4] => 215
)
--- ### 解决方案 #### 递归实现(简洁直观) 通过递归遍历树形结构,收集目标键及其所有后代: ```php function getKeyAndDescendants($tree, $targetKey) { // 目标键不存在则返回空数组 if (!isset($tree[$targetKey])) { return []; } $result = [$targetKey]; $children = $tree[$targetKey]; // 遍历子节点,递归收集子节点的后代并合并 foreach ($children as $childKey => $_) { $result = array_merge($result, getKeyAndDescendants($children, $childKey)); } return $result; }
迭代实现(避免递归深度限制)
如果树形层级极深,递归可能触发PHP栈溢出,可改用栈实现迭代遍历:
function getKeyAndDescendantsIterative($tree, $targetKey) { if (!isset($tree[$targetKey])) { return []; } $result = []; $stack = [$targetKey]; while (!empty($stack)) { $currentKey = array_pop($stack); array_unshift($result, $currentKey); // 子节点倒序入栈,保证输出顺序和递归一致 $childKeys = array_keys($tree[$currentKey]); foreach (array_reverse($childKeys) as $childKey) { array_push($stack, $childKey); } } return $result; }
使用示例
// 查找键7的结果 print_r(getKeyAndDescendants($array_tree, 7)); // 查找键163的结果 print_r(getKeyAndDescendants($array_tree, 163));
内容的提问来源于stack exchange,提问作者Redhead
相关产品推荐
相关产品推荐

