php - 对 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")
);
解决方案
求和的最快方法是索引数组,像这样
$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);
}
推荐阅读
- android - 如何让我的 Android 应用程序连接到后端通道以接收更新并触发设备中的事件?
- python - python中的字符动画不起作用
- python-3.x - 如何使用 AppiumService() 从我的 python 代码启动 appium 服务器?
- c - 一个变量名多属性
- nativescript-vue - 缺少 Nativescript vue webpack 配置
- python-3.x - Pytorch卷积神经网络(CNN)中Conv2D中in_channels和out_channels的解释
- python - Python - 如何在 AWS Lambda 上安装字体?
- python - beautifulsoup:如何为空节点赋予价值
- simpledateformat - java使用simpledateformat解析一个输入String得到ParseException,而仅仅因为一个空格
- .net-core - 将 FluentValidation 与 ASP.NET Core 3.1 和视图组件集成