在设置的范围内增加整数


Increment integer in set range

如果我想循环通过一个数组,然后使用它们作为循环增量计数器,我该怎么做?

。我有多达5个值存储在一个数组中。我想循环遍历它们,在第一个循环中,我想使用一个特定的值,然后在第二个循环中使用另一个特定的值。

下面的伪代码,但是我如何将第二个数组引入到图片中?第一个范围将是动态的,为空或最多有5个值。第二个将被修复。

$array = array(2,6,8); // Dynamic
$array2 = array(11,45,67,83,99); Fixed 5 values
foreach ($array as $value) {
    // First loop, insert or use both 2 and 11 together
    // Second loop, insert or use both 6 and 45
    // Third loop, insert or use both 8 and 67
}

使用$index => $val:

foreach ($array2 as $index => $value) {
    if ( isset($array[ $index ]) ) {
          echo $array[ $index ]; // 2, then 6, then 8
    }
    echo $value; // 11, then 45, then 67, then 83, then 99 
}

在这里看到它的行动:http://codepad.viper-7.com/gpPmUG


如果你想让它在第一个数组结束时停止,那么循环遍历第一个数组:

foreach ($array as $index => $value) {
    echo $value; // 2, then 6, then 8
    echo $array2[ $index ]; // 11, then 45, then 67
}

在这里看到它的行动:http://codepad.viper-7.com/578zfQ

你可以试试-

foreach ($array as $index => $value) {
      echo $array[ $index ]; // 2, then 6, then 8
      echo $array2[ $index ]; // 11, then 45, then 67
}

这里有一个干净简单的解决方案,它不使用无用和繁重的非标准库:

$a = count($array);
$b = count($array2);
$x = ($a > $b) ? $b : $a;
for ($i = 0; $i < $x; $i++) {
    $array[$i]; // this will be 2 the first iteration, then 6, then 8.
    $array2[$i]; // this will be 11 the first iteration, then 45, then 67.
}

我们只是使用$i来识别主for循环中两个数组的相同位置,以便将它们一起使用。主for循环将迭代正确的次数,以便两个数组都不会使用未定义的索引(导致注意错误)。

确定两个数组的最小长度

然后循环你的索引i从1到最小长度。

现在可以使用两个数组的i -th元素

这是我认为你想要的:

foreach($array as $value){
     for($x = $value; $array[$value]; $x++){
       //Do something here...
     }
}

你可以使用MultipleIterator:

$arrays = new MultipleIterator(
    MultipleIterator::MIT_NEED_ANY|MultipleIterator::MIT_KEYS_NUMERIC
);
$arrays->attachIterator(new ArrayIterator([2,6,8]));
$arrays->attachIterator(new ArrayIterator([11,45,67,83,99]));
foreach ($arrays as $value) {
    print_r($value);
}

将打印:

Array ( [0] => 2 [1] => 11 ) 
Array ( [0] => 6 [1] => 45 ) 
Array ( [0] => 8 [1] => 67 ) 
Array ( [0] => [1] => 83 ) 
Array ( [0] => [1] => 99 ) 

如果您希望它要求两个数组都有值,请将标志更改为

MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC

返回

Array ( [0] => 2 [1] => 11 ) 
Array ( [0] => 6 [1] => 45 ) 
Array ( [0] => 8 [1] => 67 )