php - PHP - 循环具有未知深度的数组的递归函数在两级后没有传递/保留父键
问题描述
我想要一些关于如何处理这个用例的建议:
我有以下未知深度的多维测试数组:
$entries =
[
[
'id' => 'Foo',
'parent' => 'root',
'logic_rules' => []
],
[
'id' => 'Bar',
'parent' => 'root',
'logic_rules' => [],
'children' => [
[
'id' => 'Foobar',
'parent' => 'Bar',
'logic_rules' => [],
'children' => [
[
'id' => 'Foobar2',
'parent' => 'Foobar',
'logic_rules' => [],
'children' => [
[
'id' => 'Foobar3',
'parent' => 'Foobar2',
'logic_rules' => []
]
]
]
]
]
]
]
];
我尝试使用这个递归函数遍历数组以执行一些逻辑(从示例中排除):
function traverse(array $entries, array &$result = [])
{
foreach ($entries as $k => $value) {
// If `logic_rules` exists proceed executing the logic
// and store the result in the same `parent -> id` position
if (array_key_exists('logic_rules', $value)) {
$result[$value['parent']][$value['id']]['logic_rules'] = time(); // some logic
}
// Re-loop if is parent
if (array_key_exists('children', $value)) {
traverse($value['children'], $result);
}
}
return $result;
}
的输出traverse($entries)
是:
Array
(
[root] => Array
(
[Foo] => Array
(
[logic_rules] => 1603091236
)
[Bar] => Array
(
[logic_rules] => 1603091236
)
)
[Bar] => Array
(
[Foobar] => Array
(
[logic_rules] => 1603091236
)
)
[Foobar] => Array
(
[Foobar2] => Array
(
[logic_rules] => 1603091236
)
)
[Foobar2] => Array
(
[Foobar3] => Array
(
[logic_rules] => 1603091236
)
)
)
但我希望这样:
Array
(
[root] => Array
(
[Foo] => Array
(
[logic_rules] => 1603091236
)
[Bar] => Array
(
[logic_rules] => 1603091236
[Foobar] => Array
(
[logic_rules] => 1603091236
[Foobar2] => Array
(
[logic_rules] => 1603091236
[Foobar3] => Array
(
[logic_rules] => 1603091236
)
)
)
)
)
)
似乎它正在跳过它的祖先。对此有何建议?
解决方案
解决方案是,refer to the results parent
因此以下深度将推动它。
看看这一行:
traverse($value['children'], $result[$value['parent']]);
此代码将为您工作:
function traverse (array $entries, array &$result = []) {
foreach ($entries as $value) {
// add your logical stuff here
$result[$value['parent']][$value['id']] = array(
'logical_rules' => time()
);
if (array_key_exists('children', $value)) {
traverse($value['children'], $result[$value['parent']]);
}
}
return $result;
}
推荐阅读
- php - 如何按名称分隔两个数组
- python - 如何在 Django 管理员中以编程方式创建具有模型权限的组?
- gnuplot - 在 gnuplot 中的圆上剪辑向量
- java - 从 PostgreSQL 数据库到 Java 应用程序的通知
- javascript - 如果 Y.axis 相同,Highchart 不显示线条
- r - rodbc 删除 odbcclose 上的 SQL Server 备份文件
- python - Python删除多行
- javascript - 带参数且不带 Javascript 的 SetTimeout 函数
- c - 在 mips32 中表示一个结构
- python-3.x - 从 pyproject.toml 文件更新包版本的最佳方法