Eri*_*ric 1 php arrays foreach
如何在循环期间修改foreach()循环中的下一个元素?我认为它与通过引用与变量交谈有关,但我不确定如何.即:
$arr = array( array('color' => 'red', 'type' => 'apple'),
array('color' => 'yellow', 'type' => 'banana'),
array('color' => 'purple', 'type' => 'grape')
);
foreach($arr as $k => $v) {
echo "<br> The ".$v['type'].' fruit is '.$v['color'];
// change the color of the next fruit?
if($v['type'] == 'apple') { $arr[$k+1]['color'] = 'green'; }
}
Run Code Online (Sandbox Code Playgroud)
我想这样告诉我香蕉是绿色的,但它固执地坚持香蕉是黄色的......
(更新:在我原来的问题中修正了一个愚蠢的逻辑错误.下面标出的答案是正确的.)
foreach通过获取数组的副本而不是通过引用来循环遍历数组.您需要使用&数组值上的&符号通过引用循环遍历数组.
foreach($arr as $k => &$v) {
echo "<br> The ".$v['type'].' fruit is '.$v['color'];
// change the color of the next fruit?
if($v['type'] == 'banana') { $arr[$k+1]['color'] = 'green'; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
706 次 |
| 最近记录: |