php 按列对多维关联数组排序并保留第一级键

iyr7buue  于 2023-03-16  发布在  PHP
关注(0)|答案(6)|浏览(126)

我有一个数组,看起来像这样:

$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");

但是这种方法覆盖了包含团队名称的键,并返回:

[
    0 => [
        'points' => 23,
        'players' => []
    ],
    1 => [
        'points' => 10,
        'players' => [],
    ]
]

有没有办法在不丢失作为数组键的teamname的情况下对数组进行排序?

blpfk2vs

blpfk2vs1#

您可以使用uasort

uasort($array, function($a, $b) {
    return $a['points'] - $b['points'];
});

此函数使用用户定义的比较函数对数组进行排序,以使数组索引保持其与关联数组元素的相关性

qmelpv7a

qmelpv7a2#

U可以按值对关联数组进行排序,如下所示

$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);
moiiocjp

moiiocjp3#

试试这个代码,希望它能工作.

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");
vbopmzt1

vbopmzt14#

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
]
yzxexxkh

yzxexxkh5#

为了完整起见,本页应该包括一个使用array_multisort()的方法--这个函数在缺省情况下将保留非数字键。
代码:(Demo

array_multisort(
    array_column($array, 'points'),
    SORT_DESC,
    $array
);

也就是说,用飞船运算符调用uasort()并没有错,注意$b数据在三路比较运算符的左边,$a在右边,实现降序排序。
代码:Demo

uasort(
    $array,
    fn($a, $b) => $b['points'] <=> $a['points']
);
hgtggwj0

hgtggwj06#

使用uasort函数,它应该保持key =〉value关联不变。
(side注意:你可以用return $a['points'] - $b['points']代替ifs,或者从php7开始用spacehsip <=> operator,thx mbomb007来更新)

相关问题