PHP: Array ordering
I have about 50 items in a list. I calculate their value using an algorythm and I add their value in an array.
Suppose I get this when the loop is over:
$vals = (51, 23, 77, 3, 8, 31, 17, 102,开发者_StackOverflow社区 87, (...));
Now, how can I get they keys of the 3 highest values in the array?
In the above example, I would like to get:
- 8 (key of 102)
- 9 (key of 87)
- 3 (key of 77)
PS: I don't want to insert those datas in a DB and then select them with Order clause, I'm sure there is an easier way around.
$vals = array(51, 23, 77, 3, 8, 31, 17, 102, 87);
arsort($vals);
$keys = array_slice(array_keys($vals), 0, 3);
var_dump($keys); // array(3) { [0]=> int(7) [1]=> int(8) [2]=> int(2) }
The result is not the same you'd like to get, because arrays in php are 0-indexed
sort them descending, extract 3. first values, done!
arsort($vals);
echo "$vals[0], $vals[1], $vals[2]";
精彩评论