提问人:george 提问时间:4/25/2022 最后编辑:marc_sgeorge 更新时间:4/30/2022 访问量:139
PHP 有条件地将嵌套数组作为函数参数传递
PHP conditionally pass nested arrays as function argument
问:
我有两个嵌套的索引数组,我想使用函数用值填充它们。
但是在有条件的基础上:如果这样,则填充第一个数组;如果这样,请填充第二个数组。
这是我得到的:
工作,但重复
$sectionCounter = 0;
foreach($sections as $section) {
if ($direction === 'up') {
$array1[$sectionCounter][] = 1;
$array1[$sectionCounter][] = 25;
// ...
} else {
$array2[$sectionCounter][] = 1;
$array2[$sectionCounter][] = 25;
// ...
}
$sectionCounter++;
}
首选(尚未工作)
function addElements($temp, $sectionCounter) {
$temp[$sectionCounter][] = 1;
$temp[$sectionCounter][] = 25;
// ...
}
foreach($sections as $section) {
if ($direction === 'up') {
addElements($array1, $sectionCounter);
} else {
addElements($array2, $sectionCounter);
}
$sectionCounter++;
}
答:
0赞
R4ncid
4/25/2022
#1
您可以尝试其他方法
$sectionCounter = 0;
$data = [
'up' => $array1,
'other' => $array2
];
foreach($sections as $section) {
$dir = $direction === 'up'? 'up': 'other';
$data[$dir][$sectionCounter][] = 1;
$data[$dir][$sectionCounter][] = 25;
// ...
$sectionCounter++;
}
$array1 = $data['up'];
$array2 = $data['other'];
评论
addElements
return $temp;
$array1 = addElements($array1, ....);
&
function addElements(&$temp, $sectionCounter)
$array1
$array2