从此Array()
我想获取amount_total
,运费和合作伙伴的价值,并由特定合作伙伴对其进行总计。例如,partner=>2665
应该有一个41.79 + 55.95的amount_total,依此类推,请帮忙。我不想通过SQL来实现,因为我也需要数据。
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
)
)
答案 0 :(得分:2)
您可以使用PHP来实现此目的,但这不是必需的。 数据库可以更有效地完成这项工作
我假设您当前的查询看起来像这样
SELECT
`amount_total`,
`amount_shipping`,
`amount_partner`,
`partner`
FROM
`salesLeads`
WHERE
[..]
MySQL为您提供了很好的聚合函数,例如SUM可以与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脚本中,您可以通过相同的方式访问它,但它具有已由合作伙伴分组和汇总的最终数字
e.g。
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print_r( $row );
}
$result->close();
}
修改强>
因为你想要一个PHP解决方案,它再次比查询两次更有效:
$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 );
答案 1 :(得分:0)
我认为循环遍历此数组并将总数存储在新数组中,同时检查in_array
(more here)就足够了。你需要做的就是每次循环一个元素,检查它是否已经在新数组中,如果是 - 执行必要的数学运算
答案 2 :(得分:0)
我会建议这样的事情:
$res['totals']=array();
foreach($result as $res)
{
$partner = $result['partner'];
$res['totals'][$partner]+=$result['total_amount'];
}
通过这种方式,您可以在一个位置获得所需的所有数据:合作伙伴数组' $ res'。
希望它对你有所帮助。