多维数组扁平化函数未按预期工作

3
我所做的就是将任意整数数组压平。
这是我的代码:
<?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
变量作用域,函数中的$flattened_list与外部的不同。 - FirstOne
1个回答

4

首先,你有一个作用域问题,即你的结果数组在函数中超出了作用域。所以只需从调用到调用将其作为参数传递即可。

其次,你还没有返回结果数组,如果想要在函数外部使用结果,则必须这样做。

已纠正代码如下:

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

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

<b>$flattened_list = flatten($list_of_lists_of_lists);</b>
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
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接