doz97171 2011-08-29 22:49
浏览 60
已采纳

php根据特定键排序多维数组

iam trying to sort this array by array[key]['premium']['Monthly'] and if there are two Monthly prices the same, then sort by quarterly, then semi-annual, then annual.

i search and couldnt figure out how to use array_multisort function.

Array (
[0] => Array (
    [product_id] => 1
    [rate] => 27.07
    [premium] => Array (
        [Annual] => 436.05
        [Semi-Annual] => 226.75
        [Quarterly] => 115.6
        [Monthly] => 37.11
    )
)
[1] => Array (
    [product_id] => 2
    [rate] => 35.00
    [premium] => Array (
        [Annual] => 565
        [Semi-Annual] => 293.8
        [Quarterly] => 149.73
        [Monthly] => 50.85
    )    
)
[2] => Array (
    [product_id] => 3
    [rate] => 30.52
    [premium] => Array (
        [Annual] => 497.8
        [Monthly] => 47.29
    )
)
)
  • 写回答

1条回答 默认 最新

  • douman6679 2011-08-29 23:09
    关注

    I think you want to use usort function, something like

    function compare($a, $b){
      $p1 = $a["premium"];
      $p2 = $b["premium"];
      if($p1["Monthly"] == $p2["Monthly"]){
         // compare by quarterly
         ...
      }else{
         if($p1["Monthly"] < $p2["Monthly"])then return -1;
         else return 1;
      }
    }
    
    usort($prices, "compare");
    

    where $prices is your array. The comparision function isn't implemented fully, just to show the idea. Also, since it looks like there might be missing items in the price array (ie last one misses Quarterly and Semi-Annual) you have to check first (before comparison) does the items exists and take appropriate action in case one or both are missing.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?