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 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改