在fo​​reach循环增加数组元素,而在PHP? [英] Increasing array elements while in foreach loop in php?

查看:209
本文介绍了在fo​​reach循环增加数组元素,而在PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的code:

<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
   print "key=>$key\n";
   if(!isset($arr['a']))
      $arr['a'] = 'apple';
}
?>

这是不是显示A。如何使用的foreach哈希表(阵列)的作品,遍历每个元素。如果列表是实现我为什么不能在运行时添加更多?

It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?

请不要告诉我,我可以做基于数字索引这项任务具有计数的帮助。

Please don't tell me that I could do this task with numeric based index with help of counting.

推荐答案

循环前阵副本Foreach源结构(的了解更多),所以你不能改变阵列的结构,等待里面的循环的新元素。你可以使用,而而不是的foreach

Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.

$arr = array();
$arr['b'] = 'book';

reset($arr);
while ($val = current($arr))
    {
    print "key=".key($arr).PHP_EOL;
    if (!isset($arr['a']))
        $arr['a'] = 'apple';
    next($arr);
    }

或者使用 ArrayIterator 用foreach,因为ArrayIterator不是数组。

Or use ArrayIterator with foreach, because ArrayIterator is not an array.

$arr = array();
$arr['b'] = 'book';

$array_iterator = new ArrayIterator($arr);


foreach($array_iterator as $key=>$val) {
   print "key=>$key\n";
   if(!isset($array_iterator['a']))
      $array_iterator['a'] = 'apple';
}

这篇关于在fo​​reach循环增加数组元素,而在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆