Selecting every nth item from an array

后端 未结 8 1828
春和景丽
春和景丽 2021-02-02 13:41

What would be the most efficient way to select every nth item from a large array? Is there a \'smart\' way to do it or is looping the only way?

Some points to c

8条回答
  •  时光说笑
    2021-02-02 14:24

    I recommend to using array_slice

    $count = count($array) ;
    for($i=205;$i<$count;$i+=205){
        $result[] = array_slice($array,$i,1);
    }
    

    If your array was numerically indexed, this would be very fast:

    $count = count($array) ;
    for($i=205;$i<$count;$i+=205){
        $result[] = $array[$i];
    }
    

提交回复
热议问题