Trying to end a loop with 10 of the lowest values out of more
I have code already that loops through each member of my website and can retrieve a particular variable开发者_如何学Python (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.
See this example in codepad: http://codepad.org/4ROaojCT
<?php
$array = array(5, 6, 1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13);
sort($array);
$array = array_slice($array, 0, 10);
print_r($array);
Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Since you have to loop through every value anyway, just add all of the values to an array and then use the sort
method 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.
Store all the members of your website in a Hash with the key being the duration and the value being a primary key or even an object containing the member's detail. Write a function that can be fed to uksort which will sort the hash based on the keys. reverse and print the top 10.
精彩评论