[英]sum of an array with specific values
I am looking for a PHP method which would allow me to calculate the sum of 2 values.我正在寻找一种 PHP 方法,它可以让我计算 2 个值的总和。 In my example I have 3 tables and I would like to add table 1 with table 3 because they have the same article_id and the same declination_id.
在我的示例中,我有 3 个表,我想将表 1 与表 3 添加在一起,因为它们具有相同的 article_id 和相同的 declination_id。
$sql = 'SELECT SUM(quantity) AS qty, SUM(quantity) * price_cost - ((SUM(quantity) * price_cost) * discount) / 100 AS cost, articles_id AS id_article, combination_id AS declinaison FROM invoice_detail';
if ($inventoryType == 'year') {
$sql .= ' WHERE DATE_FORMAT(date_add, \'%Y\') = DATE_FORMAT(NOW(), \'%Y\')';
} else {
$sql .= ' WHERE DATE_FORMAT(date_add, \'%Y-%m\') = DATE_FORMAT(NOW(), \'%Y-%m\')';
}
$sql .= ' GROUP BY invoice_id, articles_id, combination_id';
$statement = $conn->prepare($sql);
$statement->execute();
$cm = $statement->fetchAll();
foreach ($cm as $key => $item) {
// Calcul du CUM
dump($item);
}
Basically if there is in the loop the same id_article and the same id_declinaison we must sum all the values of the column "cost" in my example I would therefore like to return an array that looks like this:基本上,如果循环中有相同的 id_article 和相同的 id_declinaison,我们必须将示例中“成本”列的所有值相加,因此我想返回一个如下所示的数组:
3_1 => [
'cost' => 112.875,
'qty' => 60
];
3_2 => [
'cost' => 31.5,
'qty' => 10
];
I would like to have that at the end as a result.结果我想在最后得到那个。
This will be used to calculate the CUMP of my products.这将用于计算我的产品的 CUMP。
Thank you for your help.感谢您的帮助。
Try this.尝试这个。 See comments for explanation.
请参阅注释以获取解释。 Outputs:
输出:
array(2) {
["3_1"]=>
array(2) {
["qty"]=>
int(60)
["cost"]=>
float(112.875)
}
["3_2"]=>
array(2) {
["qty"]=>
int(10)
["cost"]=>
float(31.5)
}
}
Code:代码:
<?php
// Your example cart items.
$cartItems = [
[
'qty' => 10,
'cost' => 21.5,
'id_article' => '3',
'declinaison' => '1'
],
[
'qty' => 10,
'cost' => 31.5,
'id_article' => '3',
'declinaison' => '2'
],
[
'qty' => 50,
'cost' => 91.375,
'id_article' => '3',
'declinaison' => '1'
]
];
// Result array.
$groupedCartItems = [];
// Loop over every cart item and group them on the 'id_article_declinaison' key.
foreach ($cartItems as $cartItem)
{
$key = "{$cartItem['id_article']}_{$cartItem['declinaison']}";
if (!isset($groupedCartItems[$key]))
{
// Not yet recorded this item before, initialize it here.
$groupedCartItems[$key]['qty'] = $cartItem['qty'];
$groupedCartItems[$key]['cost'] = $cartItem['cost'];
}
else
{
// Already saw this item, add the qty and cost to its subtotal.
$groupedCartItems[$key]['qty'] += $cartItem['qty'];
$groupedCartItems[$key]['cost'] += $cartItem['cost'];
}
}
var_dump($groupedCartItems);
/*
array(2) {
["3_1"]=>
array(2) {
["qty"]=>
int(60)
["cost"]=>
float(112.875)
}
["3_2"]=>
array(2) {
["qty"]=>
int(10)
["cost"]=>
float(31.5)
}
}
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.