php - 如何使用 PHP 提取多维数组树的一部分
问题描述
我有一个巨大的动态生成的树。树是根据每个元素的“parent_id”属性从平面数组生成的。
例如,最终结果将如下所示:
Array
(
[0] => Array
(
[id] => 70
[name] => Top Corp
[parent_id] => 0
[children] => Array
(
[0] => Array
(
[id] => 43
[name] => Department
[parent_id] => 70
[children] => Array
(
[0] => Array
(
[id] => 45
[name] => Building
[parent_id] => 43
[children] => Array
(
[0] => Array
(
[id] => 75
[name] => Office
[parent_id] => 45
)
)
)
如何仅提取数组树的一部分?我应该看哪些功能或方法?
例如,我怎么说另一个子级别(可能深 20-30 级)现在是顶部。
例如,一个伪函数sliceTree(45)
应该产生以下结果,也就是从id 45
[0] => Array
(
[id] => 45
[name] => Building
[parent_id] => 43
[children] => Array
(
[0] => Array
(
[id] => 75
[name] => Office
[parent_id] => 45
)
)
)
没有办法知道树可以走多深,所以它的解决方案需要是递归的。
我尝试循环数组,寻找起始 id,但我不确定在找到该点后如何继续执行。
我提出的解决方案如下
function sliceTree($tree, $id){
$ret = [];
foreach ($tree as $out) {
// if the top level matches
if($out["id"] == $id){
array_push($ret, $out);
}
else {
if(isset($out["children"])){
foreach ($out["children"] as $c) {
if($c["id"] == $id){
array_push($ret, $c);
}
// probably needs to call itself here
}
}
}
}
return $ret;
}
哪个有效,但仅适用于顶级元素。我怎样才能进行递归并考虑多个级别的孩子?
解决方案
该sliceTree()
函数基本上查找某个id
并返回它。像这样的东西:
function sliceTree($tree, $branchId)
{
// check all branches
foreach ($tree as $branch) {
// have we found the correct branch?
if ($branch['id'] == $branchId) return $branch;
// check the children
if (isset($branch['children'])) {
$slice = sliceTree($branch['children'], $branchId);
if (isset($slice)) return $slice;
}
}
// nothing was found
return null;
}
如您所见,此例程是递归的。代码未经测试。
我很抱歉混合隐喻:树枝和孩子,但你开始了它。
这个函数比我想要的稍微复杂一些,因为在你的例子中,children
当没有孩子时,键不存在。我通常希望它在那里并且值是一个空数组。
推荐阅读
- clickhouse - 在 clickhouse 中枢轴
- java - 如何在android studio中使用液体滑动?
- javascript - 在 Spark AR Studio 中有延迟的人脸跟踪器的父对象?
- html - html 两个相邻且高度相等的 span 元素
- autodesk - Model Derivative API:桶的范围是什么?
- visual-studio - Xamarin Visual Studio 模拟器问题
- c# - SELECT 语句在 INSERT 提交事务后第一次不会返回行
- python - 使用 plot() 函数时 matplotlib 中的 RGBA 颜色“ro”无效
- kubernetes - 当 pod 或服务或端点发生变化时如何获得通知?
- html - 使用 jQuery 脚本专注于 Enter 键上的下一个输入