php - 对来自多个数组的唯一数据求和
问题描述
我有两个来自不同数据库的数组,现在我必须将它作为组合报告打印在表格中。这些数组是
array:3 [▼
0 => array:6 [▼
"count_id" => 5
"count_name" => "NE 28/1"
"order_qty" => 75100
"balance_qty" => 75100
"stock_qty" => "0"
"order_req" => 75100
]
1 => array:6 [▼
"count_id" => 13
"count_name" => "NE 20/1 KH"
"order_qty" => 2200
"balance_qty" => 2200
"stock_qty" => "48400"
"order_req" => 0.0
]
]
和第二个数组
array:2 [▼
0 => array:6 [▼
"count_id" => 13
"count_name" => "NE 20/1 KH"
"order_qty" => 2200
"balance_qty" => 2200
"stock_qty" => "45420.85"
"order_req" => 0.0
]
1 => array:6 [▼
"count_id" => 24
"count_name" => "NE 24/1 KH"
"order_qty" => 5150
"balance_qty" => 5150
"stock_qty" => "45420.85"
"order_req" => 0.0
]
]
现在我需要常见的“count_name”,如“NE 20/1 KH”值将只求和并打印一次。就像是...
array:3 [▼
0 => array:6 [▼
"count_id" => 5
"count_name" => "NE 28/1"
"order_qty" => 75100
"balance_qty" => 75100
"stock_qty" => "0"
"order_req" => 75100
]
1 => array:6 [▼
"count_id" => 13
"count_name" => "NE 20/1 KH"
"order_qty" => 4400
"balance_qty" => 4400
"stock_qty" => "96800"
"order_req" => 0.0
]
2 => array:6 [▼
"count_id" => 24
"count_name" => "NE 24/1 KH"
"order_qty" => 5150
"balance_qty" => 5150
"stock_qty" => "45420.85"
"order_req" => 0.0
]
]
我尝试通过两个 foreach 循环来做到这一点,但它没有用。它会多次打印每个数据。那么有没有人可以帮助我,拜托。
解决方案
它可以完成,但首先通过数据库查询将它们组合起来可能更容易。
// Your arrays of data
$data = [$array1, $array2];
// The fields you want to sum
$sumFields = ['order_qty', 'balance_qty', 'stock_qty', 'order_req'];
// The final array
$combined = [];
foreach ($data as $arr) {
foreach ($arr as $item) {
$key = $item['count_id'];
if (!isset($combined[$key])) {
$combined[$key] = $item;
} else {
foreach ($sumFields as $field) {
$combined[$key][$field] += $item[$field];
}
}
}
}
// Print result
print_r($combined);
推荐阅读
- javascript - 笑话路径映射错误:找不到模块 xyz 映射为:abc
- sql - Oracle 19 数据库是否支持 UUID 列?
- r - 每次在闪亮的应用程序中按下 actionButton 时,都会在存储的 csv 文件中添加一个新列
- windows - 优雅地等待/关闭的脚本/windows 命令
- python - 为什么scrapy不调用该函数?
- javascript - 如何在 javascript 中播放铃声音频(无需用户交互)?
- java - 如何添加另一个链表对象
- c# - 如何在没有 ReSharper (C#) 的情况下在 Visual Studio 中设置用于提取局部变量的键盘快捷键?
- docker - Dockerfile:计算缓存键失败:“/nginx.conf”未找到:未找到
- msal - 如何使用 MSAL 获取访问令牌