我想将+1添加到数组的元素中。如果达到限制,则增加数组的下一个元素。如果它们全部达到最大值,它将停止。
例如,数组有5个元素,最大为3 ,所有元素均从值0开始:
$arr = array(0, 0, 0, 0, 0);
答案 0 :(得分:0)
此代码可以满足您的要求,并且适用于$arr
数组中的任意数量的元素,您还可以通过更改$limit
变量来设置限制。
<?php
//This is your input
$arr = array(
0,
0,
0,
0,
0
);
//This is the maximum number
$limit = 3;
//This is your iteration
foreach( $arr as $key=>$value ){
while($value < $limit){
$value++;
$arr[$key] = $value;
echo str_replace( "\n", "", print_r($arr, true)) . PHP_EOL;
}
}
?>
运行此代码时,得到以下输出:
Array( [0] => 1 [1] => 0 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 2 [1] => 0 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 0 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 1 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 2 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 0 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 1 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 2 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 0 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 1 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 2 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 0)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 1)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 2)
Array( [0] => 3 [1] => 3 [2] => 3 [3] => 3 [4] => 3)
您要的是什么。
如果您希望对输出进行某些操作,请将行echo str_replace( "\n", "", print_r($arr, true)) . PHP_EOL;
更改为您要执行的任何操作。