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.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大