在foreach()循环期间修改数组中的下一个元素


Modify next element in array during foreach() loop

如何在循环期间修改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'; }
}

我想告诉我香蕉是绿色的,但它顽固地坚持着香蕉是黄色的。。。

(更新:修复了我原来问题中的一个愚蠢的逻辑错误。下面标记的答案是正确的。)

foreach通过获取数组的副本而不是通过引用来循环遍历数组。您需要使用数组值上的"与"answers"&"通过引用循环遍历数组。

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'; }
}
$k=array_keys($yourarray);
    for($i=0; $i<sizeof ($k); $i++) {
       if($yourarray[$k[$i]] == "something") {
           $yourarray[$k[$i+1]] = "something else"; 
       }
    }
}     

很抱歉,当我从电话回复时,格式很不稳定。。。

计数器必须保持相同的

$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'] == 'banana') { $arr[$k]['color'] = 'green'; }
  // now echo the new color from the original array 
   echo "<br> The ".$arr[$k]['type'].' fruit is now '.$arr[$k]['color'];
}