![](/img/trans.png)
[英]How to get the highest and lowest Values and sum from Multidimensional array in PHP
[英]How to get the keys from an array sorted from highest to lowest value in php?
我有一个数组例如
$pointsTotal = array('70','23','555','8789','1245');
我需要从此数组中将密钥从高到低排序。 这意味着此示例中的输出应为
array('4','5','3','1','2')
请帮忙。
我希望这段代码可以解决您的问题:
<?php
$pointsTotal = array(70,23,555,8789,1245);
arsort($pointsTotal);
$newArrForKey = array();
foreach($pointsTotal AS $key => $val){
$newArrForKey[] = $key + 1;
}
print_r($newArrForKey);
上面代码的输出是:
Array ( [0] => 4 [1] => 5 [2] => 3 [3] => 1 [4] => 2 )
使数组从1到5,并与主数组同步对其进行排序。 请记住,主数组也会被排序。 进行复制以保存它(如果需要)
$k= range(1, count($pointsTotal));
array_multisort( $pointsTotal, SORT_DESC, $k);
print_r($k);
结果
[ 4, 5, 3, 1,2 ]
尝试这个 ..
$output= ksort($pointsTotal);
下面的代码应该可以解决您的问题。
<?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";
}
?>
脚步:-
rsort()
对复制的数组进行反向排序。 威廉·弗朗西斯·戈麦斯(William Francis Gomes)的答案是正确的,但使用循环并使用密集数组可能会提高效率,此外,在课堂和教学中,这会杀死您。
这是一个无循环的单行纯C解决方案,在任何情况下都可以使用:
arsort($pointsTotal);
$result = array_keys(array_flip(array_map(function($el){ return $el + 1; }, array_flip($pointsTotal))));
结果
Array ( [0] => 4 [1] => 5 [2] => 3 [3] => 1 [4] => 2 )
如果您想保留原始密钥:
arsort($pointsTotal);
$result = array_values(array_flip($pointsTotal));
结果:
Array ( [0] => 3 [1] => 4 [2] => 2 [3] => 0 [4] => 1 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.