Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用模数获取具有偏移量的第n个子项_Php_Loops_Modulus - Fatal编程技术网

在PHP中使用模数获取具有偏移量的第n个子项

在PHP中使用模数获取具有偏移量的第n个子项,php,loops,modulus,Php,Loops,Modulus,在循环中迭代时,我在if语句中使用了模运算符,很容易获得n结果,如下所示: // Get 5th item in series if ($variable->array_item % 5 == 0) { echo $variable->array_item; } 如何获得偏移量为3(即3、8、13、18、23等)的系列中的第5项 我已经看到了一些方法,但我正在寻找一个规范的答案,现在在S.O.上我真的没有看到一个; $iterator = 0; $step = 3; whil

在循环中迭代时,我在
if
语句中使用了模运算符,很容易获得
n
结果,如下所示:

// Get 5th item in series
if ($variable->array_item % 5 == 0) {
  echo $variable->array_item;
}
如何获得偏移量为3(即3、8、13、18、23等)的系列中的第5项

我已经看到了一些方法,但我正在寻找一个规范的答案,现在在S.O.上我真的没有看到一个;
$iterator = 0;
$step = 3;

while($iterator < count($collection))
{
 echo $collection[$iterator]
 $iterator += $step
}
$step=3; while($iterator
$iterator=0;
$step=3;
while($iterator
您的代码特别要求可以被5整除的数字,而您需要的是数字3、8、13、18、23等。使用与您拥有的代码几乎相同的代码可以很容易做到这一点:

// set up some test data
$testArray = [];

for ($i = 1; $i <= 30; ++$i) {
    $testArray[$i] = "Testing {$i}";
}

// here's where the actual work happens
foreach ($testArray as $key => $value) {
    if ($key % 5 == 3) { // <-- note 3, not 0
        echo "Found $value\n";
    }
}
//设置一些测试数据
$testArray=[];

对于($i=1;$i您的代码特别要求可以被5整除的数字,而您需要的是数字3、8、13、18、23等。使用与您拥有的代码几乎相同的代码可以轻松做到这一点:

// set up some test data
$testArray = [];

for ($i = 1; $i <= 30; ++$i) {
    $testArray[$i] = "Testing {$i}";
}

// here's where the actual work happens
foreach ($testArray as $key => $value) {
    if ($key % 5 == 3) { // <-- note 3, not 0
        echo "Found $value\n";
    }
}
//设置一些测试数据
$testArray=[];

对于($i=1;$i)当你说“如何使用偏移量”时,你能澄清一下你的意思吗?谢谢!更新的问题-希望现在更清楚。模数似乎对偏移量不起作用。对不起,现在是周末,我可能错过了一些非常明显的东西,因为我仍然不理解你的问题。你的意思是“我想要第三、第八、第十三、第十八项”?哈,对吧?我也快结束了!我正试图得到第五个结果,偏移量为3。所以,3、8、13、18、23等等。我现在明白了;我已经发布了一个答案,完全符合你的要求。当你说,“你如何使用偏移量?”“,你能澄清一下你的意思吗?谢谢!更新的问题-希望现在更清楚。模数似乎不太适合补偿。对不起,现在是周末,我可能错过了一些非常明显的东西,因为我仍然不理解你的问题。你的意思是“我想要第3、第8、第13、第18项”哈,对吗?我也快结束了!我正试图得到偏移量为3的第五个结果。所以3,8,13,18,23等等。我现在明白了;我已经发布了一个答案,完全符合你的要求。有趣的方法,我会尝试一下。有趣的方法,我会尝试一下。