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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊