How to “flatten” a multi-dimensional array to simple one in PHP?

前端 未结 23 2116
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

It\'s probably beginner question but I\'m going through documentation for longer time already and I can\'t find any solution. I thought I could use implode for each dimensio

23条回答
  •  醉话见心
    2020-11-22 01:11

    Another method from PHP's user comments (simplified) and here:

    function array_flatten_recursive($array) { 
       if (!$array) return false;
       $flat = array();
       $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
       foreach ($RII as $value) $flat[] = $value;
       return $flat;
    }
    

    The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
    This will output:

    $array = array( 
        'A' => array('B' => array( 1, 2, 3)), 
        'C' => array(4, 5) 
    ); 
    print_r(array_flatten_recursive($array)); 
    
    #Returns: 
    Array ( 
        [0] => 1 
        [1] => 2 
        [2] => 3 
        [3] => 4 
        [4] => 5 
    )
    

提交回复
热议问题