我有一个像这样的数组:
$this->wordswithdata = [
'team1' => [
'points' => 10,
'players' => [],
],
'team2' => [
'points' => 23,
'players' => []
]
];
,我想按照每个球队的得分从高到低对这些球队进行排序。我试过了:
function sort_by_points($a,$b)
{
if ($a['points'] == $b['points']) return 0;
return ($a['points'] < $b['points']) ? 1 : -1;
}
usort($this->wordswithdata, "sortbycount");
但是这种方法覆盖了包含teamname的键并返回:
[
0 => [
'points' => 23,
'players' => []
],
1 => [
'points' => 10,
'players' => [],
]
]
是否有任何方法来排序数组而不丢失teamnames作为数组键?
使用sort函数,它应该保留键=>值关联完整。
(旁注:您可以使用return $a['points'] - $b['points']
代替if,或者在php7中使用spacehsip <=>
操作符,感谢mbom007用于更新)
您可以使用uasort
:
uasort($array, function($a, $b) {
return $a['points'] - $b['points'];
});
该函数使用用户定义的比较函数对数组进行排序,使数组索引与所关联的数组元素保持相关性。
您可以按其值对关联数组进行排序,如下所示
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
function Ascending($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
function Descending($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
echo "Ascending order" ;
uasort($age,"Ascending");
print_r($age);
echo "</br>Descending order" ;
uasort($age,"Descending");
print_r($age);
为了完整起见,该页应该包括使用array_multisort()
的方法—该函数默认情况下将保留非数字键。
代码(演示):
array_multisort(
array_column($array, 'points'),
SORT_DESC,
$array
);
也就是说,用宇宙飞船操作符调用uasort()
并没有错。注意,$b
数据位于三通比较运算符的左侧,$a
数据位于右侧,实现降序排序。
代码:演示
uasort(
$array,
fn($a, $b) => $b['points'] <=> $a['points']
);
试一下这段代码,希望能成功。
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"points");
its working fine i giving example
that array need sort
$sumarray=array [▼
484 => 54.7875
486 => 53.5375
487 => 52.9125
488 => 52.2875
493 => 54.7875
]
$original=$sumarray;
$svalue=array_values($sumarray);
rsort($svalue);
$sorted=array();
foreach ($svalue as $key => $value) {
$kk=array_search($value,$sumarray);
$sorted[$kk]=$value;
unset($sumarray[$kk]);
}
print_r($original);
print_r($svalue);
print_r($sorted);
//out put
array:5 [▼
484 => 54.7875
486 => 53.5375
487 => 52.9125
488 => 52.2875
493 => 54.7875
]
array:5 [▼
0 => 54.7875
1 => 54.7875
2 => 53.5375
3 => 52.9125
4 => 52.2875
]
array:5 [▼
484 => 54.7875
493 => 54.7875
486 => 53.5375
487 => 52.9125
488 => 52.2875
]