[英]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(即3、8、13、18、23等)的系列中的第五項?
我已經看到了幾種方法,但是我正在尋找一個規范的答案,我現在真的還沒有看到這樣的方法。
您的代碼特別要求可以被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";
}
}
$iterator = 0;
$step = 3;
while($iterator < count($collection))
{
echo $collection[$iterator]
$iterator += $step
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.