从数组和总计中获取唯一值 [英] get unique value from array and sum totals
问题描述
从这个 Array()
中我想获取 amount_total
的值,运输和合作伙伴并将其总计由特定的伙伴。因此,例如 partner => 2665
应该具有的total_total为41.79 + 55.95,依此类推,请提供帮助。我不想通过SQL进行操作,因为我也需要数据。
From this Array()
I want to grab the values of amount_total
, shipping and partner and total them up by specific partner. So for example the partner=>2665
should have a amount_total of 41.79 + 55.95 and so on please help. I don't want to do it through SQL because I need the data as it is as well.
Array
(
[0] => Array
(
[amount_total] => 41.79
[amount_shipping] => 4.99
[amount_partner] => 14.8
[partner] => 2665
)
[1] => Array
(
[amount_total] => 55.95
[amount_shipping] => 19.96
[amount_partner] => 11
[partner] => 2665
)
[2] => Array
(
[amount_total] => 51.96
[amount_shipping] => 7.98
[amount_partner] => 23.98
[partner] => 51754
)
[3] => Array
(
[amount_total] => 24.55
[amount_shipping] => 4.99
[amount_partner] => 5.67
[partner] => 11513
)
)
推荐答案
您可以使用PHP实现此目的,但这不是必需的。
数据库可以更有效地做到这一点
You could use PHP to achieve this, but this won't be necessary. The database can do this much more efficiently
我假设您当前的查询看起来像这样
I assume your current query looks something like this
SELECT
`amount_total`,
`amount_shipping`,
`amount_partner`,
`partner`
FROM
`salesLeads`
WHERE
[..]
MySQL给你很好可以使用 SUM 之类的汇总函数与 GROUP BY
MySQL gives you nice aggregate functions like SUM you can use with GROUP BY
SELECT
SUM( `amount_total` ) AS `amount_total`,
SUM( `amount_shipping` ) AS `amount_shipping`,
SUM( `amount_partner` ) AS `amount_partner`.
`partner`
FROM
`salesLeads`
WHERE
[..]
GROUP BY
`partner`
在您的PHP脚本中,您可以通过相同的方式进行访问,但是最终的数字已经由合作伙伴进行了分组和汇总
in your PHP script you access this the same way but it has the final numbers grouped and summarized by partner already
例如
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print_r( $row );
}
$result->close();
}
编辑
因为您想要一个PHP解决方案,它比两次查询更有效:
Because you wanted a PHP solution, which again is more efficient than querying twice:
$partnerSums = array();
while ( $row = $result->fetch_assoc() ) {
if ( !array_key_exists( $row['partner'], $partnerSums ) {
$partnerSums[$row['partner']] = $row;
} else {
$partnerSums[$row['partner']]['amount_total'] += $row['amount_total'];
$partnerSums[$row['partner']]['amount_shipping'] += $row['amount_shipping'];
$partnerSums[$row['partner']]['amount_partner'] += $row['amount_partner'];
}
}
print_r( $partnerSums );
这篇关于从数组和总计中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!