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

前端 未结 23 2111
没有蜡笔的小新
没有蜡笔的小新 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:29

    You can use the flatten function from Non-standard PHP library (NSPL). It works with arrays and any iterable data structures.

    assert([1, 2, 3, 4, 5, 6, 7, 8, 9] === flatten([[1, [2, [3]]], [[[4, 5, 6]]], 7, 8, [9]]));
    
    0 讨论(0)
  • 2020-11-22 01:31

    If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.

    <?php  
    
    $array = [1,2,3,[5,6,7]];
    $nu_array = null;
    $callback = function ( $item ) use(&$callback, &$nu_array) {
        if (!is_array($item)) {
        $nu_array[] = $item;
        }
        else
        if ( is_array( $item ) ) {
         foreach( array_values($item) as $v) {
             if ( !(is_array($v))) {
                 $nu_array[] = $v;
             }
             else
             { 
                 $callback( $v );
             continue;
             }    
         }
        }
    };
    
    array_walk($array, $callback);
    print_r($nu_array);
    

    The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:

    <?php  
    
    $array = [1,2,3,[5,6,7]];
    
    $nu_array = [];
    array_walk_recursive($array, function ( $item ) use(&$nu_array )
                         {
                             $nu_array[] = $item;
                         }
    );
    print_r($nu_array);
    

    See live code

    This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.

    0 讨论(0)
  • 2020-11-22 01:34

    Use array_walk_recursive

    <?php
    
    $aNonFlat = array(
        1,
        2,
        array(
            3,
            4,
            5,
            array(
                6,
                7
            ),
            8,
            9,
        ),
        10,
        11
    );
    
    $objTmp = (object) array('aFlat' => array());
    
    array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
    
    var_dump($objTmp->aFlat);
    
    /*
    array(11) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
      [3]=>
      int(4)
      [4]=>
      int(5)
      [5]=>
      int(6)
      [6]=>
      int(7)
      [7]=>
      int(8)
      [8]=>
      int(9)
      [9]=>
      int(10)
      [10]=>
      int(11)
    }
    */
    
    ?>
    

    Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)

    0 讨论(0)
  • 2020-11-22 01:34

    This is a one line, SUPER easy to use:

    $result = array();
    array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });
    

    It is very easy to understand, inside the anonymous function/closure. $v is the value of your $original_array.

    0 讨论(0)
  • 2020-11-22 01:34

    In PHP>=5.3 and based on Luc M's answer (the first one) you can make use of closures like this

    array_walk_recursive($aNonFlat, function(&$v, $k, &$t){$t->aFlat[] = $v;}, $objTmp);
    

    I love this because I don't have to surround the function's code with quotes like when using create_function()

    0 讨论(0)
提交回复
热议问题