如何获取具有指数增长索引位置的字符串项

How to get string items with exponential increase index locations

如何获取索引位置 1,2,8,9,15,16 (covid,1234,sars,2345,ebv,2345) 中的字符串项。

$str2 = "false|covid|1234|yes|no|no|556|true|sars|2345|no|no|yes|235|true|ebv|2345|no|no|yes|235";

$var2=explode('|',$str2);

$leg = -7;
$lag = -4;
foreach($var2 as $key => $row2){
$leg = $leg + 7;
$lag = $lag + 7;


if($key > $leg && $key < $lag){

echo $row2.",";
}

}

在这种情况下,我认为使用步长为 7 的 for 循环更容易,因为您似乎希望项目偏移 7。

如果您从索引 2 开始循环,您就可以直接访问您想要的项目。

$str2 = "false|covid|1234|yes|no|no|556|true|sars|2345|no|no|yes|235|true|ebv|2345|no|no|yes|235";
$var2 = explode('|', $str2);

$itemsOfInterest = [];
for ($i = 2; $i < count($var2); $i += 7) {
    $itemsOfInterest[] = $var2[$i - 1]; // Index 1, 1 + 7, 1 + 7 + 7, etc.
    $itemsOfInterest[] = $var2[$i]; // Index 2, 2 + 7, etc.
}

echo '<pre>';
print_r($itemsOfInterest);
echo '</pre>';

打印:

Array
(
    [0] => covid
    [1] => 1234
    [2] => sars
    [3] => 2345
    [4] => ebv
    [5] => 2345
)