Recursively loop through multidimensional to create flat array

后端 未结 3 1997
我在风中等你
我在风中等你 2021-01-26 16:36

I have a multidimensional array that looks like this:

$trees = array(
    array(
        \'name\' => \'Parent\',
        \'__children\' => array(
                  


        
3条回答
  •  走了就别回头了
    2021-01-26 17:25

    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

    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

提交回复
热议问题