[英]Get three highest values from the array
I want to get three highes values from my array, but it should be sorted properly by keys also. 我想从我的数组中获得三个高值,但它也应该通过键正确排序。
I have this code: 我有这个代码:
<?php
$a = array(130, 1805, 1337);
arsort($a);
print_r($a);
?>
The output of the above is following: 以上输出如下:
Array
(
[1] => 1805
[2] => 1337
[0] => 130
)
Its working fine, but I want it additionaly to sort its keys from the highest to the lowest value. 它的工作正常,但我希望它还可以从最高到最低值对它进行排序。
Example: 例:
Array
(
[2] => 1805
[1] => 1337
[0] => 130
)
To be clear: I want it be to sorted by the keys: array key number 2 will be always used for the highest value, array key number 0 will be always used for the lowest value. 要明确:我希望按键排序:数组键号2将始终用于最高值,数组键号0将始终用于最低值。
How can I do that? 我怎样才能做到这一点?
/let me know if you don't understand something. 如果你不明白,请告诉我。
rsort($array);
$top3 = array_reverse(array_slice($array, 0, 3));
You should use array_reverse
for this. 你应该使用
array_reverse
。
<?php
$a = array(130, 1805, 1337);
arsort($a);
print_r(array_reverse($a));
?>
Easily accessed by $a[0]
, $a[1]
, $[2]
to get your highest values. 通过
$a[0]
, $a[1]
, $[2]
轻松访问以获得最高价值。
<?php
$array = array(130, 1805, 1337);
sort($array);
for ($i=0; $i <= count($array)-1; $i++)
$arr[]=$array[$i];
print_r($arr);
?>
I would try: 我会尝试:
<?php
$a = array(130, 1805, 1337);
arsort($a);
$a = array_reverse($a);
I couldn't get the output you described with any of the answers already posted (tested via IDEOne.com). 我无法通过已发布的任何答案(通过IDEOne.com测试)获得您描述的输出。
Here is my solution ( demo ): 这是我的解决方案( 演示 ):
$a = array(130, 1805, 1337);
$keys = array_keys($a); rsort($keys, SORT_NUMERIC);
$values = array_values($a); rsort($values, SORT_NUMERIC);
$a = array_combine(array_slice($keys, 0, 3), array_slice($values, 0, 3));
print_r($a);
Output: 输出:
Array
(
[2] => 1805
[1] => 1337
[0] => 130
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.