为什么不能在多个foreach循环中使用数组?
这是一个简单的问题,但我无法找到答案。我不是在寻找对我的代码的更正,只是关于这个问题的教育。
该数组是在第一个 foreach 开始之前定义的,因此我可以在循环之外使用它。
$arrayVar = array();
foreach ($variables as $key => $variable){
$arrayVar = array(
'name' => $squad['full_name'],
'position' => $squad['position']
);
}
这将用数据填充数组。但是,当在另一个循环中使用时,数组会重置而不是追加到末尾。
编辑:约翰的回答解决了这个问题。简单地包含方括号为我节省了大约 1000 行。
回答
您在每次迭代中不断覆盖您的数组,而不是附加到它。
$arrayVar = array();
foreach ($variables as $key => $variable){
$arrayVar[] = array( // <= Add to array instead of overwriting it
'name' => $squad['full_name'],
'position' => $squad['position']
);
}
- @M.Whitmore 1) The `[]` notation shown in this answer is equivalent to `array_push`, but more commonly used for its conciseness. 2) It's not about using it in "remaining loops", it's about _the loop you've shown us here_ being incorrect.