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

时间:2012-02-28 00:56:07

标签: 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'; }
}

我想告诉我香蕉是绿色的,但它固执地坚持香蕉是黄色的......

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

3 个答案:

答案 0 :(得分:5)

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

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'; }
}

答案 1 :(得分:0)

$k=array_keys($yourarray);
    for($i=0; $i<sizeof ($k); $i++) {
       if($yourarray[$k[$i]] == "something") {
           $yourarray[$k[$i+1]] = "something else"; 
       }
    }
}     
抱歉格式化很难得,因为我正在通过电话回复......

答案 2 :(得分:-1)

计数器必须保持不变

$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'];
}