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:-
rsort()
to reverse sort this copied array. 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.