简体   繁体   English

PHP的array_multisort不工作

[英]php array_multisort not working

I'm having this issue where I want to sorty a multidimensional array based on 2 parameters 我遇到了这个问题,我想根据2个参数对多维数组进行排序

I build my array like this: 我这样构建数组:

$teamList[$t['id']] = array(
    'id'     => $t['id'], 
    'name'   => $t['name'], 
    'score'  => $score, 
    'points' => $array
);

I then sort like this: 然后,我这样排序:

foreach ($teamList as $key => $row) {
        $score[$key]  = $row['score'];
        $points[$key] = $row['points'];    
}
array_multisort($score, SORT_DESC, $points, SORT_DESC, $teamList);  

But the $teamList remains unsorted? 但是$ teamList仍未排序吗?

You can easily use a user defined compare function instead of doing all the copying of values and abusing array_multisort() . 您可以轻松地使用用户定义的比较函数,而不是进行所有值的复制和滥用array_multisort()

function sortByScoreAndPoints($a, $b) {
  if ($a['score'] == $b['score']) {
    if ($a['points'] == $b['points']) {
      return 0;
    }
    return ($a['points'] > $b['points']) ? -1 : 1;
  }
  return ($a['score'] > $b['score']) ? -1 : 1;
}

uasort($teamlist, 'sortByScoreAndPoints');

The sort function has to accept two parameters which can have arbitrary names, but $a and $b is used in the docs. sort函数必须接受两个可以具有任意名称的参数,但是$ a和$ b在文档中使用。 During sorting, PHP passes any two values of the array as $a and $b and expects an answer in which order they should appear. 在排序过程中,PHP将数组的两个值分别传递为$ a和$ b,并期望按它们出现的顺序给出答案。 Your sort function has to return -1 if $a should appear first, 0 if they are equal, or 1 if $a should appear last, compared to $b. 与$ b相比,如果$ a应该首先出现,则排序函数必须返回-1;如果相等则返回0;如果$ a应该最后出现,则返回1。

My code first tests if the scores are equal. 我的代码首先测试分数是否相等。 If not, the last return will compare which score is higher ( $a > $b ), and the highes score goes into the list first (if a is bigger than b, return -1 to say a goes first). 如果不是,则最后一个返回值将比较哪个分数更高($ a> $ b),并且最高分数首先进入列表(如果a大于b,则返回-1表示a首先进入)。

If the scores are equal, points will be tested. 如果分数相等,将测试分数。 If they are not equal, the comparison takes place again. 如果它们不相等,则再次进行比较。 Otherwise 0 is returned. 否则返回0。

Any entry in the team list with equal score and points might appear in arbitrary location in the result (but not random - the same input array will always be sorted the same), because there is no further ordering specified. 团队列表中得分和得分相等的任何条目都可能出现在结果中的任意位置(但不是随机的-相同的输入数组将始终按相同的顺序排序),因为没有指定进一步的顺序。 You might easily extend your sorting by adding another comparison for the name or the id, if you like. 如果愿意,您可以通过添加名称或ID的另一个比较来轻松扩展排序。

If you want your sorted array to be renumbered starting at 0, use usort() instead of uasort() . 如果您希望从0开始重新排序数组,请使用usort()而不是uasort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM