简体   繁体   English

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

[英]php sort a multidimensional Array bases on specific keys

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. iam尝试按array [key] ['premium'] ['Monthly']对该数组进行排序,如果有两个相同的月度价格,则按季度排序,然后按半年,然后按年度排序。

i search and couldnt figure out how to use array_multisort function. 我搜索,无法弄清楚如何使用array_multisort函数。

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
    )
)
)

I think you want to use usort function, something like 我认为您想使用usort函数,例如

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. 其中$prices是您的数组。 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. 另外,由于价格数组中可能似乎缺少商品(即最后一个商品错过了季度和半年度商品),因此您必须先检查(比较之前)商品是否存在,并采取适当的措施以防丢失一个或两个商品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM