Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

php - How to get string items with exponential increase index locations

How to get string items within 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.",";
}

}
question from:https://stackoverflow.com/questions/65864412/how-to-get-string-items-with-exponential-increase-index-locations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In this case I think it is easier to use a for loop with a step size of 7 as it seems you want the items that are offset by 7.

If you start the loop at index 2, you can then directly access the items you want.

$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>';

Prints:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...