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.
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.
<?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 = array(130, 1805, 1337);
arsort($a);
array_reverse($a);
Would produce:
Array
(
[2] => 1807
[1] => 1337
[0] => 130
)
You can find out more about it here .
<?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).
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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.