gpt4 book ai didi

PHP 向 foreach 中使用的数组添加新键

转载 作者:可可西里 更新时间:2023-11-01 00:20:44 25 4
gpt4 key购买 nike

如何添加到我正在使用 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()

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

查看差异 here .

关于PHP 向 foreach 中使用的数组添加新键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com