gpt4 book ai didi

php - 如何在 php foreach 循环中保持运行总计

转载 作者:行者123 更新时间:2023-11-29 19:10:46 28 4
gpt4 key购买 nike

我正在尝试创建一个表来显示三种不同类型的成员的成员数据 - 它应该显示每天添加的成员数量,然后需要有一列来保存迄今为止的累计总月数三种不同类型的成员(member)。示例:

三月份添加的成员:

日期      A 类      A 类合计      B 类      B 类合计

1             23                23                   16                  16
2             13                36                   13                  29
3             16                52                   17                  46

我的查询如下所示:

$results=$wpdb->get_results("SELECT DAY(Subscription_Start_Date) as dayOfMonth, COUNT(a.user_id) as typeA, COUNT(b.user_id) as typeB, COUNT(c.user_id) as typeC
FROM users u
LEFT OUTER JOIN typeAUser a ON u.type_id = a.User_Id
LEFT OUTER JOIN typeBUser b ON u.type_id = b.User_Id
LEFT OUTER JOIN typeCUser c ON u.type_id = c.user_Id AND c.phone_opt_out != '1'
WHERE MONTH(Subscription_Start_Date) = MONTH(curdate()) AND YEAR(Subscription_Start_Date) = YEAR(curdate())
GROUP BY DAY(Subscription_Start_Date)
ORDER BY DAY(Subscription_Start_Date)");

我使用 foreach 循环将数据输出到表中,如下所示:

$resultTable = "<table><thead>
<tr><td colspan='7'>Month to Date Members Added $currentMonth</td></tr>
<tr>
<th>Day of the Month</th>
<th>Type A</th>
<th>Type A Month to Date</th>
<th>Type B</th>
<th>Type B Month to Date</th>
<th>Type C</th>
<th>Type C Month to Date</th>
</tr></thead><tbody>";

foreach($results as $r){
$aMemPerDay = $r->typeA;
$bMemPerDay = $r->typeB;
$cMemPerDay = $r->typeC;

$resultTable .= "<tr>
<td>$r->dayOfMonth</td>
<td>$aMemPerDay</td>
<td>???</td>
<td>$bMemPerDay</td>
<td>???</td>
<td>$cMemPerDay</td>
<td>???</td>
</tr>";
}
$resultTable .="</tbody></table>";

echo $resultTable;

该查询返回我需要的每天添加的成员数量的信息,但我不知道如何保持每天增加的运行总数。我尝试了很多事情,但似乎没有任何效果。我尝试在每个成员类型的 foreach 中实现此解决方案的变体,但是当我将 $totalA 变量放入表中时,它只是打印出数组:

$totalA = array();
$runningSumA = 0;

foreach ($aMemPerDay as $aMem) {
$runningSumA += $aMem;
$totalA[] = $runningSum;
}

我什至尝试在查询中使用 MySQL 变量(因为每个月只有 30 天,我认为这不会太麻烦),但我也无法在那里获得累积结果。我知道那里可能有一些可管理的答案,但我似乎无法想出它。任何方向将不胜感激!

最佳答案

$TotalA = 0;
$TotalB = 0;
$TotalC = 0;

foreach($results as $r){
$aMemPerDay = $r->typeA;
$bMemPerDay = $r->typeB;
$cMemPerDay = $r->typeC;

$TotalA += $aMemPerDay;
$TotalB += $bMemPerDay;
$TotalC += $bMemPerDay;

$resultTable .= "<tr>
<td>$r->dayOfMonth</td>
<td>$aMemPerDay</td>
<td>???</td>
<td>$bMemPerDay</td>
<td>???</td>
<td>$cMemPerDay</td>
<td>???</td>
</tr>";
}

关于php - 如何在 php foreach 循环中保持运行总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43101043/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com