Selecting every nth item from an array

后端 未结 8 1840
春和景丽
春和景丽 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:12

    A foreach loop provides the fastest iteration over your large array based on comparison testing. I'd stick with something similar to what you have unless somebody wishes to solve the problem with loop unrolling.

    This answer should run quicker.

    $result = array();
    $i = 0;
    foreach($source as $value) {
        if ($i++ % 205 == 0) {
            $result[] = $value;
        }
    }
    

    I don't have time to test, but you might be able to use a variation of @haim's solution if you first numerically index the array. It's worth trying to see if you can receive any gains over my previous solution:

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

    This would largely depend on how optimized the function array_values is. It could very well perform horribly.

    0 讨论(0)
  • 2021-02-02 14:13

    You can't move the array pointer, it seems, more than once at a time. I would personally use this:

    reset($source);
    $next = true;
    while($next === true){
        $result[] = current($source);
        for(i=0;i<205;i++){
            $next = next($source);
        }
    }
    

    If someone can find a function that can move the array pointer more than just one step at a time, you will have a better answer. I think this is good though.

    0 讨论(0)
  • 2021-02-02 14:15

    If this really is a bottleneck, you might want to consider rethinking your design in order to make it numerically indexed.

    EDIT: Or create and maintain a seperate array with just the 205th items (which gets updated at insert or something like that).

    0 讨论(0)
  • 2021-02-02 14:15
    • Create a two dimentional array [205][N]
    • Load data into array
    • Access 205th element for every N

    May sound silly but by definition it is fastest since you access memory locations directly and do not perform any comparisons.

    0 讨论(0)
  • 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];
    }
    
    0 讨论(0)
  • 2021-02-02 14:25

    You could use array_keys to work only on the array keys.

    $keys = array_keys($array);
    for ($i=0, $n=min(count($keys), 130000); $i<$n; $i += 205) {
        $result[] = $array[$keys[$i]];
    }
    
    0 讨论(0)
提交回复
热议问题