Search code examples
phpphp-5.3php-5.4

How to turn a php array of unlimited(unknown) depth into a single array?


Array
(
    [72] => Array
        (
            [id] => 70
            [login] => test100
            [parent_id] => 1
            [type_id] => 1
            [position] => 1
            [user_id] => 72
            [children] => Array
                (
                )

        )

    [73] => Array
        (
            [id] => 72
            [login] => test101
            [parent_id] => 1
            [type_id] => 1
            [position] => 2
            [user_id] => 73
            [children] => Array
                (
                    [74] => Array
                        (
                            [id] => 74
                            [login] => test105
                            [parent_id] => 72
                            [type_id] => 1
                            [position] => 1
                            [user_id] => 74
                            [children] => Array
                                (
                                )

                        )

                )

        )

)

I have this array for example, but the depth can be unlimited, how to convert an ulimited or unknown of depth multidimensional array to single array?


Solution

  • <?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);
    
    ?>