递归遍历多维以创建平面数组 [英] Recursively loop through multidimensional to create flat array
本文介绍了递归遍历多维以创建平面数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多维数组,如下所示:
I have a multidimensional array that looks like this:
$trees = array(
array(
'name' => 'Parent',
'__children' => array(
array(
'name' => 'Child'
),
array(
'name' => 'Second Child'
)
)
)
);
数组的深度未知,我需要递归展平它.所以看起来更像这样:
The depth of the array is unknown and I need to recursively flatten it. So it looks more like this:
array(
array(
'name' => 'Parent'
),
array(
'name' => 'Child'
),
array(
'name' => 'Second Child'
)
)
我认为类似的方法可能有用:
I thought something like this might work:
public function flattenTree($trees, $tree = array())
{
foreach($trees as $item){
//$i = 1, 2, then 3
$i = count($tree);
$tree[$i] = array('name' => $item['name']);
if(isset($item['__children']))
$this->flattenTree($item['__children'], $tree);
}
return $tree;
}
但这只能给我:(
Array
(
[0] => Array
(
[name] => Parent
)
)
我不确定该怎么做.有可能吗?
I am unsure how to do this. Is it possible?
作为奖励,我真的需要输出数组看起来像这样(注意名称值已更改):)
As a bonus I really need the output array to look like this(notice the name value changed) :)
array(
array(
'name' => 'Parent'
),
array(
'name' => 'Parent Child'
),
array(
'name' => 'Parent Second Child'
)
)
非常感谢您对此提供的帮助.期待解决方案.我很沮丧!
Thanks a ton for the help on this one. Looking forward to the solutions. I am stumped!
推荐答案
我最终使用了类似的东西,并从@Pankrates答案中得到了很多启发.非常感谢.
I ended up using something like this, with a lot of inspiration from @Pankrates answer. Thanks a lot.
$trees = $multidimensionalArray;
$flat = array();
$postRepository->flattenRecursive($flat, $trees);
//$flat is now a flattened version of $multidimensionalArray
var_dump($flat);
public function flattenRecursive(array &$flat, array $nested, $parentPrepend = false)
{
foreach( $nested as $item ){
$flat[] = array(
'name' => ($parentPrepend) ? $parentPrepend . '/' . $item['name'] : $item['name']
);
$prepend = $parentPrepend ? $parentPrepend . '/' . $item['name'] : $item['name'];
if(isset($item['__children']))
$this->flattenRecursive($flat, $item['__children'], $prepend);
}
}
这篇关于递归遍历多维以创建平面数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文