如何获取维数组中的值?

时间:2010-12-13 03:04:37

标签: php arrays

如何获取此数组的值:

Array
(

    [0] => 20
    [1] => Array
        (
            [0] => 21
            [1] => 22
            [2] => Array
                (
                    [0] => 23
                    [1] => Array
                        (
                            [0] => 52
                            [1] => 
                        )

                )

        )

)

我想得到这个值:20,21,22,23和52。

提前致谢! :)

2 个答案:

答案 0 :(得分:1)

此代码应该这样做:

function flatten_array($a)
{
    $retval = array();
    foreach ($a as $value)
    {
        if (is_array($value))
            $retval = array_merge($retval,flatten_array($value));
        else
            $retval []= $value;
    }
    return $retval;
}

答案 1 :(得分:0)

我想得到这个值:20,21,22,23和52。

转换为递归地获取原始数组的所有值的数组。使用标准 array_walk_recursive 功能......


$test_array = array(
    20,
    array(
        21,
        22,
        array(
            23,
            array(
                52,
                null
                )
            )
        )
    );

$array_extracted = array();

array_walk_recursive($test_array, function($val, $key) use (&$array_extracted) {if (!is_array($val)) $array_extracted[] = $val;});

print_r($array_extracted);
/*
gives: Array
(
    [0] => 20
    [1] => 21
    [2] => 22
    [3] => 23
    [4] => 52
    [5] =>
)
*/