下面提供的代码是我的真实代码的摘要.我想使用多个循环将多个数组中的项添加到最终数组中.但我也想多次添加相同的值,因此将所有内容包装在另一个循环中.这听起来很混乱,但我认为代码解释得很好.为什么我只从一个循环得到结果?换句话说,为什么$total只包含6个元素的六个元素而不是30个元素(一个六五次),正如人们对for循环所期望的那样?
for ($counter = 1; $counter < 5; $counter++) {
$first_arr = array('one', 'two', 'three');
$second_arr = array('four', 'five', 'six');
$total = array();
foreach ($first_arr as $x) {
$total[] = $x;
}
foreach ($second_arr as $x) {
$total[] = $x;
}
}
var_dump($total);
Run Code Online (Sandbox Code Playgroud)
因为您正在重置$total外循环的每次迭代.在外部循环之前声明它,您的问题将得到解决.
像这样:
$total = array();
$first_arr = array('one', 'two', 'three');
$second_arr = array('four', 'five', 'six');
for ($counter = 1; $counter < 5; $counter++) {
// assuming $first_arr and $second_arr have numerical keys
// which they do, in this example
$total = array_merge($total, $first_arr, $second_arr);
}
var_dump($total);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |