为foreach中使用的数组添加新键


PHP Adding new key to the array used in 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()那样给PHP一个限制(数组的大小)或for(),在那里你传递了一个限制。

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

感谢Scowler的解决方案。这是在评论中发布的,尽管他回复了一个答案,但它不像他第一个评论建议那么简单。

$t =array('item');
$c = 1;
for ($x=0; $x<count($t); $x++) {
    $item = $t[$x];
    echo '--> '.$item.$c;
    if ($c < 10) {
        array_push($t,'anotheritem');
    }
    $c++;
}

作品太棒了!Count ($t)在每次执行循环时都会重新求值。