1

So, I have this:

$abc = array('a','b','c');
foreach ($abc as $k => &$a) {
    echo $a;
    if ($k == 1)
        $abc[] = 'd';
}

Work's as expected, iterating through the foreach 4 times and giving me:

abcd

But now, when I have this:

$myvar = $this->someModel->return_an_array_as_result(); // returns array([0] => array('a' => 'b'))

foreach ($myvar as $myvar_key => &$mv){
    $myvar[] = array('e' => 'f');
    var_dump($myvar);
    if ($myvar_key == 5) die;
}

The foreach only runs once.

Any thoughts on how foreach works when resetting the internal pointer?

4

2 回答 2

1

我明白你的意思,你可以使用ArrayObjectwhich 将允许追加到数组,而你仍然循环遍历数组

$myvar = new ArrayObject(array('a' => 'b'));
$x = 0;
foreach ( $myvar as $myvar_key => $mv ) {
    $myvar->append(array('e' => 'f'));
    if (($x >= 4))
        break;
    $x ++;
}
var_dump($myvar);

输出

object(ArrayObject)[1]
  public 'a' => string 'b' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
于 2012-10-08T18:13:25.413 回答
1

That's because foreach is actually working on a copy of the array. If you're planning on modifying the array while you're iterating over it, use a traditional for loop.

For more information, see the PHP docs on foreach. Also, if you're looking to modify elements while iterating, you can &$reference them (more information about this also found in the foreach docs).

于 2012-10-08T18:01:27.387 回答