douyou2368 2018-10-12 10:26
浏览 68

通过PHP中对象值的总和对多维数组进行排序

I have the below multi dimensional array of products. Each array is a pair of products that make a product set, I need to order the multi dimensional array by the total price of each product set.

array(4) {
  [0]=>
  array(2) {
    ["product1"]=>
    object(stdClass)#5075 (2) {
      ["product_id"]=>
      string(4) "9416"
      ["price"]=>
      string(6) "110.00"
    }
    ["product2"]=>
    object(stdClass)#5077 (2) {
      ["product_id"]=>
      string(4) "9431"
      ["price"]=>
      string(6) "100.00"
    }
  }
  [1]=>
  array(2) {
    ["product1"]=>
    object(stdClass)#5065 (2) {
      ["product_id"]=>
      string(4) "1254"
      ["price"]=>
      string(6) "75.00"
    }
    ["product2"]=>
    object(stdClass)#5067 (2) {
      ["product_id"]=>
      string(4) "9431"
      ["price"]=>
      string(6) "62.00"
    }
  }
  [2]=>
  array(2) {
    ["product1"]=>
    object(stdClass)#5055 (2) {
      ["product_id"]=>
      string(4) "9416"
      ["price"]=>
      string(6) "45.00"
    }
    ["product2"]=>
    object(stdClass)#5057 (2) {
      ["product_id"]=>
      string(4) "9431"
      ["price"]=>
      string(6) "50.00"
    }
  }
  [3]=>
  array(2) {
    ["product1"]=>
    object(stdClass)#5045 (2) {
      ["product_id"]=>
      string(4) "9416"
      ["price"]=>
      string(6) "60.00"
    }
    ["product2"]=>
    object(stdClass)#5047 (2) {
      ["product_id"]=>
      string(4) "9431"
      ["price"]=>
      string(6) "25.00"
    }
  }
}

I need to sort the multi-dimensional array by the total sum of product1 + product2 in each array in ascending order. For example [1] should be above [0] as 75+62 is less than 110 +100.

If anyone can help me with this it would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • doume1301 2018-10-12 10:33
    关注

    You can use usort() for this purpose:-

    function comparePrice($a,$b)
    {
      $a_price = $a['product1']->price + $a['product2']->price;
      $b_price = $b['product1']->price + $b['product2']->price;
      if ($a_price ==$b_price) return 0;
      return ($a_price<$b_price)? -1:1;
    }
    usort($array,'comparePrice');
    

    A hardcoded working example:- https://3v4l.org/mTfu6

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分