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

时间:2017-03-29 18:10:54

标签: php mysql loops foreach

我正在尝试创建一个显示三种不同类型成员的成员数据的表 - 它应该显示每天添加的成员数量,然后需要一个列保持累计的月总数三种不同类型的成员。例如:

3月份增加的成员:

日期类型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天,我认为它不会过于繁琐),但我也无法获得累积结果。我知道那里可能有一些可管理的答案,但我似乎无法想出它。任何方向都将不胜感激!

1 个答案:

答案 0 :(得分:0)

$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>";
}