编程语言
首页 > 编程语言> > PHP为foreach中使用的数组添加新密钥

PHP为foreach中使用的数组添加新密钥

作者:互联网

如何添加到我正在使用foreach的数组?

例如:

$t =array('item');
$c = 1;
foreach ($t as $item) {
    echo '--> '.$item.$c;
    if ($c < 10) {
        array_push($t,'anotheritem');
    }
}

这似乎只产生一个值(‘item1’).似乎$t仅被评估一次(在foreach使用的第一时间),而不是在它进入循环之后.

解决方法:

foreach()将处理作为静态结构传递给它的数组,就迭代次数而言,它不能是动态的.您可以通过引用(& $value)传递迭代值来更改值,但不能在同一控件结构中添加新值.

对于()

for()将允许您添加新的限制,每次都会评估您传递的限制,因此count($your_array)可以是动态的.例:

$original = array('one', 'two', 'three');
for($i = 0; $i < count($original); $i++) {
    echo $original[$i] . PHP_EOL;
    if($i === 2)
        $original[] = 'four (another one)';
};

输出:

one
two
three
four (another one)

而()

您还可以使用while(true){do}方法定义自己的自定义while()循环结构.

免责声明:确保您这样做是为了定义逻辑停止位置的上限.你基本上承担了确保循环在这里停止的责任,而不是给予像foreach()那样的限制(数组大小)或者你传递限制的().

$original = array('one', 'two', 'three');
// Define some parameters for this example
$finished = false;
$i = 0;
$start = 1;
$limit = 5;

while(!$finished) {
    if(isset($original[$i])) {
        // Custom scenario where you'll add new values
        if($i > $start && $i <= $start + $limit) {
            // ($i-1) is purely for demonstration
            $original[] = 'New value' . ($i-1);
        }

        // Regular loop behavior... output and increment
        echo $original[$i++] . PHP_EOL;
    } else {
        // Stop the loop!
        $finished = true;
    }
}

见差异here.

标签:array-push,php,foreach
来源: https://codeday.me/bug/20190728/1561610.html