问题描述
如何获取索引位置 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
)