[英]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. 使数组从1到5,并与主数组同步对其进行排序。 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. 然后,我们使用rsort()
对复制的数组进行反向排序。 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. 威廉·弗朗西斯·戈麦斯(William Francis Gomes)的答案是正确的,但使用循环并使用密集数组可能会提高效率,此外,在课堂和教学中,这会杀死您。
Here is a one line pure C solution without loop that will works in any cases : 这是一个无循环的单行纯C解决方案,在任何情况下都可以使用:
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.