I have code already that loops through each member of my website and can retrieve a particular variable (in this case it is $duration).
What I am trying to do is find people with the 10 lowest durations, and put them into an ordered array or list and then loop through the 10 and echo it out.
As a use case, let’s pretend that out of 100 members, 10 people have duration 10, 20, 30, 40, etc…, and we’ll pretend the other 90 members have durations somewhere between 101-1000.
As I loop through each member, I want to see if that member’s duration value is lower than any of the 10 I already have in some container (array?), and at the end be able to echo out the 10 from lowest to highest.
Since you have to loop through every value anyway, just add all of the values to an array and then use the
sortmethod and take the first ten items (0-9). Here is the documentation on how exactly to use this method:http://www.php.net/manual/en/function.sort.php
The benefit of this solution is that it will re-order the values so that key 0 corresponds with the lowest value. It also has the option to change what type of comparison you are doing (text, numeric, etc.)
You could try to sort every time you find a new value (insert the new value and drop the highest value). That would save you the memory storage for the array but it will cost you in processing power when you do a comparison on each value. Even with optimization it probably won’t be good enough.
If you really didn’t want to put every item in the array, you could create an array of 50 members (or whatever magic number you wanted to use). You could populate it with the first 50 durations and then sort it. Then you could add 40 more items to array positions 10-49 and sort it again. You could repeat that over and over, keeping your lowest ten items every time you add new durations. That way you could balance the performance hit of sorting every item with the memory hit of storing every item. You could dial it in by changing the array size.