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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作