PHP中的数组:将1加到具有限制的元素+增加下一个元素

时间:2018-10-16 10:02:09

标签: php

我想将+1添加到数组的元素中。如果达到限制,则增加数组的下一个元素。如果它们全部达到最大值,它将停止。

例如,数组有5个元素,最大为3 ,所有元素均从值0开始:

$arr = array(0, 0, 0, 0, 0);
  • 迭代1(加+1):1、0、0、0、0
  • =最大值是例如3
  • 迭代2(加+1):2、0、0、0、0
  • 迭代3(加+1):3,0,0,0,0
  • =已达到最大值
  • 迭代4(加上+1):3(不是4),1(因为前一个有溢出),0、0、0
  • 迭代5(加+1):3、2、0、0、0
  • ...
  • 迭代n-1(加+1):3、3、3、3、3
  • =达到最大值
  • 迭代n(加+1):3、3、3、3、3,(1)
  • 结束

1 个答案:

答案 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;更改为您要执行的任何操作。