doulao2128 2016-02-22 21:01
浏览 54
已采纳

基于count()对关联数组进行排序,并按字母顺序对具有相同count()的数组进行排序

I have an array in the following format:

array("Vancouver FIR"=>array("data:data:data:data", "more:data", "even:more:data"), "Toronto FIR"=>array("data", "more:data"));

This array in reality is much larger and changes every three minutes.

I need this array to be sorted by the count() of the associative array keys. Furthermore if the count() is the same, they need to be sorted alphabetically.

I have tried using usort/uksort with no success?? This is mostly because one provides you with the values and one provides you with the keys, but in this case I need both. I am looking into making my own sorting algorithm but don't know where to start. Any suggestions?? Thanks in advance

What I have tried:

usort($sorted, function($x, $y) {
    if (count($x) == count($y)) {
        return strcmp(key($x),key($y));
    } else {
        return $x > $y ? -1 : 1;
    }
});
  • 写回答

1条回答 默认 最新

  • duanji9311 2016-02-22 21:31
    关注

    You could use array_multisort:

    // input data
    $data = array(
        "Vancouver FIR"=>array("data:data", "more:data", "even:more:data"), 
        "Toronto FIR"=>array("data", "more:data"),
        "Montreal FIR"=>array("data", "more:data", "lalala"),
    );
    
    // get the counts from the original array
    $counts = array_map(function($v) { return count($v); }, $data);
    // get the keys from the original array
    $keys = array_keys($data);
    
    // sort first by counts, then by keys, and 
    // let the original data array follow the same re-ordering.
    array_multisort($counts, SORT_ASC, $keys, SORT_ASC, $data);
    

    If you need to sort one or both of these dimensions descending, then replace SORT_ASC by SORT_DESC where needed.

    Remark

    It may be tempting to sort the original array twice, first on keys and then on counts, but this is not guaranteed to work, because of the following phrase in the PHP documentation on sorting arrays:

    If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

    Practically this means that PHP array sorting methods do not guarantee that if two items have equal sort values that they will retain their relative position as before the sort started. They could be swapped.

    This then of course kills the idea of sorting in two steps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含