【发布时间】:2015-09-16 09:21:36
【问题描述】:
我有一个如下所示的数组:
[
'applicant' => [
'user' => [
'username' => true,
'password' => true,
'data' => [
'value' => true,
'anotherValue' => true
]
]
]
]
我想要做的是将该数组转换为如下所示的数组:
[
'applicant.user.username',
'applicant.user.password',
'applicant.user.data.value',
'applicant.user.data.anotherValue'
]
基本上,我需要以某种方式循环遍历嵌套数组,并且每次到达叶节点时,将该节点的整个路径保存为点分隔字符串。
只有以true 为值的键是叶节点,其他每个节点将始终是一个数组。我将如何实现这一目标?
编辑
这是我迄今为止尝试过的,但没有给出预期的结果:
$tree = $this->getTree(); // Returns the above nested array
$crumbs = [];
$recurse = function ($tree, &$currentTree = []) use (&$recurse, &$crumbs)
{
foreach ($tree as $branch => $value)
{
if (is_array($value))
{
$currentTree[] = $branch;
$recurse($value, $currentTree);
}
else
{
$crumbs[] = implode('.', $currentTree);
}
}
};
$recurse($tree);
【问题讨论】:
-
到目前为止你已经尝试过什么。也发布你的尝试..
-
我已经在上面发布了我的尝试
标签: php arrays recursion hierarchy breadcrumbs