简体   繁体   中英

How to get the keys from an array sorted from highest to lowest value in php?

I have an array for example

$pointsTotal = array('70','23','555','8789','1245');

I need to sort get the keys from this array from higest to lowest. That means the output in this example should be

array('4','5','3','1','2')

Please help.

I hope this code will solve your problem:

<?php    
$pointsTotal = array(70,23,555,8789,1245);
arsort($pointsTotal);
$newArrForKey = array();
foreach($pointsTotal AS $key => $val){
    $newArrForKey[] = $key + 1;
}
print_r($newArrForKey);

And the output of above code is:

Array ( [0] => 4 [1] => 5 [2] => 3 [3] => 1 [4] => 2 )

make array from 1 to 5 and sort it synchronously with main array. Keep in mind that main array will be sorted too. Make a copy to save it, if needed

$k= range(1, count($pointsTotal));
array_multisort( $pointsTotal, SORT_DESC, $k);

print_r($k);

result

[ 4, 5, 3, 1,2 ]

尝试这个 ..

 $output= ksort($pointsTotal);

The below code should solve your problem.

<?php

$pointsTotal = array('70','23','555','8789','1245');

// Copy pointsTotal, as rsort will modify it

$rsortedPointsTotal = $pointsTotal;

rsort($rsortedPointsTotal);

$pointsIndices = array();

$currentIndex = 0;

foreach($rsortedPointsTotal as $point) {
  $pointsIndices[$currentIndex] = array_search($point, $pointsTotal) + 1;
  $currentIndex++;
}

echo "\n";

foreach ($pointsIndices as $index) {
  echo $index."\n";
}

?>

Steps:-

  1. First, we copy the original array
  2. We then use rsort() to reverse sort this copied array.
  3. For each index of this reverse sorted array, we find its index in the original array.
  4. Taadaa! Done.

William Francis Gomes answer is correct but uses a loop and for dense arrays that could be a problem for efficiency, beside, in class and oop this will kills you.

Here is a one line pure C solution without loop that will works in any cases :

arsort($pointsTotal);
$result = array_keys(array_flip(array_map(function($el){ return $el + 1; }, array_flip($pointsTotal))));

result

Array ( [0] => 4 [1] => 5 [2] => 3 [3] => 1 [4] => 2 )

In case you want to retain the original keys:

arsort($pointsTotal);
$result = array_values(array_flip($pointsTotal));

result:

Array ( [0] => 3 [1] => 4 [2] => 2 [3] => 0 [4] => 1 )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM