首页 > 解决方案 > 对 php 数组进行分组的最佳方法是什么?

问题描述

例如,我有这个数组:

$bills = array(
                 array("bill_id"=>"1", "product_id"=>"1", "total"=>"10"),
                 array("bill_id"=>"2", "product_id"=>"2", "total"=>"20"),
                 array("bill_id"=>"3", "product_id"=>"1", "total"=>"30"),
                 array("bill_id"=>"4", "product_id"=>"1", "total"=>"40"),
                 array("bill_id"=>"5", "product_id"=>"2", "total"=>"50")
            );

我们需要将每个产品的总数添加到一个数组中,即从上述数组生成以下数组的最佳干净快速方法是什么:

 $products = array(
                array("product_id"=>"1", "total"=>"80"),
                array("product_id"=>"2", "total"=>"70")
            );

标签: phparrays

解决方案


求和的最快方法是索引数组,像这样

$products = array();

foreach ($bills as $bill) {
    $key = $bill['product_id'];
    if (isset($products[$key])) {
        $products[$key]['total'] += $bill['total'];
    } else {
        $products[$key] = $bill;
    }
}

var_dump($products);

输出

array(2) {
  [1]=>
  array(3) {
    ["bill_id"]=>
    string(1) "1"
    ["product_id"]=>
    string(1) "1"
    ["total"]=>
    int(80)
  }
  [2]=>
  array(3) {
    ["bill_id"]=>
    string(1) "2"
    ["product_id"]=>
    string(1) "2"
    ["total"]=>
    int(70)
  }
}

浏览发票清单

foreach($products as $key=>$bill) {
    var_dump($bill);
}

推荐阅读