【发布时间】:2019-10-21 17:37:52
【问题描述】:
所以,基本上我要做的是获取数组子元素的组合,例如我得到了数组:
[
"name" => "Item1",
"children" =>
[
"name" => "Item2",
"children" => [
["name" => "Item3"],
["name" => "Item4"]
]
],
["name" => "Item5"]
];
我尝试使用我在 stackoverflow 上获得的一些功能,但我只能让它同时使用所有这些功能,我只是得到了
[
"Item4" => "Item1/Item2/Item4",
"Item5" => "Item1/Item5"
];
输出应该是
[
"Item1" => "Item1",
"Item2" => "Item1/Item2",
"Item3" => "Item1/Item2/Item3"
"Item4" => "Item1/Item2/Item4"
"Item5" => "Item1/Item5"
];
如被问及,我之前使用的函数:
function flatten($arr) {
$lst = [];
/* Iterate over each item at the current level */
foreach ($arr as $key => $item) {
/* Get the "prefix" of the URL */
$prefix = $item['slug'];
/* Check if it has children */
if (array_key_exists('children', $item) and sizeof($item['children'])) {
/* Get the suffixes recursively */
$suffixes = flatten($item['children']);
/* Add it to the current prefix */
foreach($suffixes as $suffix) {
$url = $prefix . '/' . $suffix;
$lst[$item['id']] = $url;
}
} else {
/* If there are no children, just add the
* current prefix to the list */
$lst[$item['id']] = $prefix;
}
}
return $lst;
}
【问题讨论】:
标签: php arrays laravel multidimensional-array