在foreach中动态更改数组 [英] dynamically changing array in foreach

查看:164
本文介绍了在foreach中动态更改数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式更改由foreach处理的数组?我尝试了这个脚本

is it possible somehow change array which is processed by foreach? I tried this script

$iterator = 10;
$cat = array(1 => 'a',2 => 'b',3 => 'c');

foreach ($cat as $k => $c)
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;  
}

但是它并没有改变'foreached'数组. foreach的输出是

but it isn't changing the 'foreached' array. The output from foreach is

abc

abc

但是foreach之后数组中的var_dump是

but var_dump from array after foreach is

array(6){[1] =>字符串(1)"a" [2] =>字符串(1)"b" [3] =>字符串(1)"c" [10] => int (10)[11] => int(11)[12] => int(12)}

array(6) { [1]=> string(1) "a" [2]=> string(1) "b" [3]=> string(1) "c" [10]=> int(10) [11]=> int(11) [12]=> int(12) }

这意味着在foreach睫毛夹中添加了10、11、12,但是foreach没有遍历它们?有可能这样做吗?还是我需要制作2个foreach Cyclus?

That means 10,11,12 were added in foreach cyclus, but foreach didn't iterate over them? Is it possible to do that? Or do I need to make 2foreach cyclus?

推荐答案

<?php
$iterator = 10;
$cat = array(1 => 'a',2 => 'b',3 => 'c');

foreach ($cat as $k => &$c)//observe the '&'
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;
} 
?>

这篇关于在foreach中动态更改数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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