如何将无限(未知)深度的php数组转换为单个数组?

时间:2014-05-24 20:07:12

标签: php php-5.3 php-5.4

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
                                (
                                )

                        )

                )

        )

)

我有这个数组,但深度可以是无限的,如何将ulimited或未知的深度多维数组转换为单个数组?

1 个答案:

答案 0 :(得分:2)

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

?>