Selecting every nth item from an array

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

    I think the solution to this problem doesn't lie in any PHP syntax but in the design of your code.

    You could either make the array numerically indexed (might not be plausible for your application), keep track of every 205th item, or only search the array once (cache a list of each 205th item).

    In my mind, keeping track of each 205th item would be easier to implement. You'd just keep a count of all the items in a database or something, and every time an item is added, check the modulo of the count. If you have another 205th item, add it to the array. For when items are deleted though, this would be trickier. You might have to re-check the entire array to realign all your 205th items.

    Doing this would be simpler if you could start at the deleted item and move forward, but again this would only work for numerically indexed arrays -- and if that were true, you wouldn't have to move forward at all, you would just do a little maths to re-figure it out.

    • Numerical indexes -- better long-term solution but harder to implement
    • Keeping track -- easier to implement, but you'd have to get dirty again when you delete items
    • Caching items -- you should probably do this for the other two solutions as well, but on its own, it would be fast until the array were modified, in which case you would probably have to re-do it.

提交回复
热议问题