简体   繁体   English

递归遍历多维以创建平面数组

[英]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;
}

But this is only gives me :(但这只是给了我:(

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!我难住了!

Ok I have given this a shot and although it might not be the cleanest solution I think it should get the job done: 好的,我给了这个机会,尽管它可能不是最干净的解决方案,但我认为它应该可以完成工作:

function flattenRecursive(array &$flat, $parentkey, array $nested){

    $flag       = true;
    $prepend    = '';

    foreach( $nested as $k => $val ){
        if( is_array($val) ){

            if ( $k == '__children' && $flag) {
                $prepend = end($flat);
                $flag = true;
            } else {
                $flag = false;
            }

            flattenRecursive($flat, $prepend , $val);

        } else {

            $flat[] = $parentkey . ' ' . $val;

        }
    }
}

function flatten(array $nested){
    $flat = array();
    flattenRecursive($flat, '', $nested);
    return $flat;
}

On a test array (with extra nesting for extra testing) as follows 在测试数组上(带有用于额外测试的额外嵌套),如下所示

$trees = array(
            array(
                'name' => 'Parent',
                '__children' => array(
                    array(
                        'name' => 'Child',
                        '__children' => array(
                            array(
                                'name' => 'Nest One'
                            ),
                            array(
                                'name' => 'Nest Two'
                            )
                        )
                    ),
                    array(
                        'name' => 'Second Child'
                    )
                )
            )
        );

$result = flatten($trees);

the var_dump of $result looks like the following $resultvar_dump如下所示

array(5) {
  [0]=>
  string(7) " Parent"
  [1]=>
  string(13) " Parent Child"
  [2]=>
  string(22) " Parent Child Nest One"
  [3]=>
  string(22) " Parent Child Nest Two"
  [4]=>
  string(20) " Parent Second Child"
 }

Hopefully this was what you were looking for 希望这就是您想要的

I ended up using something like this, with a lot of inspiration from @Pankrates answer. 我最终使用了类似的方法,并从@Pankrates答案中获得了很多启发。 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);
    }
}

code

<?php


$output_array = array();

$input_array  = array(
    array(
        'name'=>'Parent',
        '__children' => array(
            array(
                'name' => 'Child'
            ),
            array(
                'name' => 'Second Child'
            )
        )
    )
);

echo"<pre>";
print_r($input_array);
echo"</pre>";


function flatten($arr){
    global $output_array;
    if(is_array($arr)){
        foreach($arr as $key=>$value){
            if($key=="name" && !is_array($value)){
                $output_array[] = array($key=>$value);
            }
            elseif(is_array($value)){
                flatten($value);
            }
        }
    }
}

flatten($input_array);

echo"<pre>";
print_r($output_array);
echo"</pre>";

Output 输出量

//Input array
Array
(
    [0] => Array
        (
            [name] => Parent
            [__children] => Array
                (
                    [0] => Array
                        (
                            [name] => Child
                        )

                    [1] => Array
                        (
                            [name] => Second Child
                        )

                )

        )

)

//Output Array
Array
(
    [0] => Array
        (
            [name] => Parent
        )

    [1] => Array
        (
            [name] => Child
        )

    [2] => Array
        (
            [name] => Second Child
        )

)

I have similar logic problem, I used @Mike answer with some refactoring.我有类似的逻辑问题,我使用 @Mike 回答进行了一些重构。

public function flattenRecursive(array &$flat, array $nested, $parentPrepend = false)
{
    foreach( $nested as $item ){
        $prepend = $parentPrepend ? $parentPrepend . '/' . $item['name'] : $item['name'];
        $flat[] = array(
            'name' => $prepend
        );
        if(isset($item['__children']))
            $this->flattenRecursive($flat, $item['__children'], $prepend);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM