PHP创建嵌套数组中每个值的面包屑列表 [英] PHP Create breadcrumb list of every value in nested array
问题描述
我有一个看起来像下面的数组:
I have an array that looks like the following:
[
'applicant' => [
'user' => [
'username' => true,
'password' => true,
'data' => [
'value' => true,
'anotherValue' => true
]
]
]
]
我想做的就是将该数组转换为看起来像这样的数组:
What I want to be able to do is convert that array into an array that looks like:
[
'applicant.user.username',
'applicant.user.password',
'applicant.user.data.value',
'applicant.user.data.anotherValue'
]
基本上,我需要以某种方式遍历嵌套数组,并且每次到达叶节点时,将到该节点的整个路径保存为点分隔的字符串.
Basically, I need to somehow loop through the nested array and every time a leaf node is reached, save the entire path to that node as a dot separated string.
只有以true
为值的键是叶节点,其他所有节点将始终是数组.我将如何实现这一目标?
Only keys with true
as a value are leaf nodes, every other node will always be an array. How would I go about accomplishing this?
修改
这是我到目前为止尝试过的,但是没有给出预期的结果:
This is what I have tried so far, but doesnt give the intended results:
$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);
推荐答案
此功能可以满足您的要求:
This function does what you want:
function flattenArray($arr) {
$output = [];
foreach ($arr as $key => $value) {
if (is_array($value)) {
foreach(flattenArray($value) as $flattenKey => $flattenValue) {
$output["${key}.${flattenKey}"] = $flattenValue;
}
} else {
$output[$key] = $value;
}
}
return $output;
}
您可以在此处看到它运行.
这篇关于PHP创建嵌套数组中每个值的面包屑列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!