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.

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

报告相同问题?