Php 用于展平多维数组的函数';I don’我没有按预期工作
我所要做的就是展平任意整数数组 这是我的密码:Php 用于展平多维数组的函数';I don’我没有按预期工作,php,arrays,function,recursion,foreach,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{
<?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);
?>
我不知道为什么。我用Python编写了完全相同的代码,效果很好
你们能指出我哪里出错了吗?首先,您有一个作用域问题,您的结果数组超出了函数的作用域。因此,只需将其作为参数从一个调用传递到另一个调用 其次,如果要在函数之外使用结果,也不返回结果数组,这是必须的 更正代码:
$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);
变量范围,函数中的
$flatten_列表
与外部列表不同
$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
)