猿问

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

            );


烙印99
浏览 103回答 2
2回答

白衣非少年

求和的最快方法是索引数组,像这样$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);}

守着一只汪

最简单的方法是单遍循环。$byProduct = [];foreach($bills as $bill){    $key = $bill['product_id'];    if (!isset($byProduct[$key])) {        $byProduct[$key] = [            'product_id' => $key,            'total' => 0        ];    }    $byProduct[$key]['total'] += $bill['total'];}结果var_dump($byProduct):array(2) {  [1] =>  array(2) {    'product_id' =>    string(1) "1"    'total' =>    int(80)  }  [2] =>  array(2) {    'product_id' =>    string(1) "2"    'total' =>    int(70)  }}另一种方法是使用array_walk,但在复杂性方面几乎相同:$byProduct = [];array_walk($bills, function(&$bill) use (&$byProduct) {    $key = $bill['product_id'];    if (!isset($byProduct[$key])) {        $byProduct[$key] = [            'product_id' => $key,            'total' => 0        ];    }    $byProduct[$key]['total'] += $bill['total'];});
随时随地看视频慕课网APP
我要回答