使用模数在 PHP 中获取具有偏移量的 nth-child

Getting nth-child with an offset in PHP with modulus

在遍历循环时,我在 if 语句中使用模数运算符很容易获得 nth 结果,如下所示:

// Get 5th item in series
if ($variable->array_item % 5 == 0) {
  echo $variable->array_item;
}

如何获得偏移量为 3 的系列中的第 5 个项目(即 3、8、13、18、23 等)?

我已经看到了几种方法,但我正在寻找一个规范的答案,但我真的没有在 S.O 上看到一个。现在。

$iterator = 0;
$step = 3;

while($iterator < count($collection))
{
 echo $collection[$iterator]
 $iterator += $step
}

您的代码特别要求可以被 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";
    }
}