展平多维数组的功能并不像预期的那样工作

时间:2015-12-30 23:59:41

标签: php arrays function recursion foreach

我要做的就是压平任意整数数组。

这是我的代码:

<?php
$list_of_lists_of_lists = [[1, 2, [3]], [4, 3, 4, [5, 3, 4]], 3];
$flattened_list = [];

function flatten($l){
    foreach ($l as $value) {
        if (is_array($value)) {
            flatten($value);
        }else{
            $flattened_list[] = $value;
        }
    }
}

flatten($list_of_lists_of_lists);
print_r($flattened_list);
?>

当我运行此代码时,我得到了这个:

Array ( )

我不知道为什么。我在Python中使用完全相同的代码并且工作正常。

你们可以指出,我哪里出错了?

1 个答案:

答案 0 :(得分:5)

首先你有一个范围问题,你的结果数组超出了函数的范围。所以只需将它作为参数从call到call传递。

其次,如果你想在函数之外使用结果,你也不会返回你必须做的结果数组。

更正后的代码:

$list_of_lists_of_lists = [[1, 2, [3]], [4, 3, 4, [5, 3, 4]], 3];

function flatten($l, $flattened_list = []){
    foreach ($l as $value) {
        if(is_array($value)) {
            $flattened_list = flatten($value, $flattened_list);
        } else {
            $flattened_list[] = $value;
        }
    }
    return $flattened_list;
}

$flattened_list = flatten($list_of_lists_of_lists);
print_r($flattened_list);

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 3
    [5] => 4
    [6] => 5
    [7] => 3
    [8] => 4
    [9] => 3
)
相关问题