Foreach Buckle in PHP - by looping a series of results, displaying them in a single line of table in HTML?

advertisements

I have a table of orders that I am querying for totals, and I want to display them all by quarter. Here is the query:

SELECT shipping_number, SUM(qty) AS qty, SUM(cost) AS cost,
QUARTER( TIME ) AS quarter
FROM order_items
WHERE 1
GROUP BY quarter, shipping_number
ORDER BY quarter, shipping_number

And I have a simple table row in which I want to display these results in:

echo "<tr>";
echo '<th colspan="2" style="text-align: right !important; ">TOTAL QUEBEC - EASTERN CANADA</th>';
echo "<th>Amount<br />Quantity</th>";
foreach($results as $r) {
    if($r->shipping_number == "2326244" OR $r->shipping_number == "8451211"){
        if($r->quarter == "1"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td>&nbsp;</td>"; }
        if($r->quarter == "2"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td>&nbsp;</td>"; }
        if($r->quarter == "3"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td>&nbsp;</td>"; }
        if($r->quarter == "4"){ echo "<td>$r->cost $<br />$r->qty</td>"; } else { echo "<td>&nbsp;</td>"; }
    }
}
echo "</tr>";

Except that, obviously, the foreach loop goes through the results twice, resulting in not 4 cells being created but 8.

Sample results

How the data is output right now

Question

How do I output this on a single line, so that the data is either queried and formatted in a way that makes sense to run it only through one loop (or how do I output a single row of data from multiple loops?)

How would I do that?

Keep in mind, I have multiple shipping_numbers (clients) that might apply for a single table, so I need all of their totals combined in a single result, except separated by quarters (months, and so on - but those are separate queries).


You could do something like this without rewriting the query:

$totals = array();
$totals["1"] = 0;
$totals["2"] = 0;
$totals["3"] = 0;
$totals["4"] = 0;
foreach($results as $result)
{
    if($result->shipping_number == "2326244" || $result->shipping_number == "8451211")
        $total[$result->quarter] += $result->cost;
}
foreach($totals as $total)
{
    echo "<td>".$total."</td>";
}