PHP表与循环内的小计行

时间:2014-10-27 21:05:58

标签: php mysql

我正在尝试在数组中的表中创建一个行,除了各行之外,该行还将在循环中包含小计行。

数据:

symbol => AAA, quantity => 100
symbol => AAA, quantity => 50
symbol => AAA, quantity => 20
symbol => BBB, quantity => 100
symbol => BBB, quantity => 10

我的代码:

echo "<table>\n";

$sql = "SELECT * FROM transactions WHERE account_id = '$account_id' ORDER BY symbol ASC";
$result = mysqli_query($con,$sql);
$numofrows = mysqli_num_rows($result);

for($i = 0; $i < $numofrows; $i++) {
$row = mysqli_fetch_array($result);

echo "<tr>\n";

echo "<td>".$row['symbol']."</td><td>".$row['quantity']."</td>\n";

echo "</tr>\n";
}
echo "</table>\n";

我想要的输出是什么:

<table>
<tr>//subtotal row
<td>AAA</td>
<td>170</td>
</tr>
<tr>
<td>AAA</td>
<td>100</td>
</tr>    
<tr>
<td>AAA</td>
<td>50</td>
</tr>    
<tr>
<td>AAA</td>
<td>20</td>
</tr>    
<tr>
<td>BBB</td>//subtotal row
<td>110</td>
</tr>    
<tr>
<td>BBB</td>
<td>100</td>
</tr>
<tr>
<td>BBB</td>
<td>10</td>
</tr>
</table>

1 个答案:

答案 0 :(得分:0)

下面。这可以做你想要的。我尽可能地评论。

<?php
$sql = "SELECT * FROM transactions WHERE account_id = '$account_id' ORDER BY symbol ASC";
$result = mysqli_query($con,$sql);
$numofrows = mysqli_num_rows($result);

//temp data store for the table
$tmp = array();
//temp data store for the totals
$totals = array();
//temp data store for the totals
$costs = array();


for($i = 0; $i < $numofrows; $i++) {
    $row = mysqli_fetch_array($result);

    //store in variables
    $sym = $row['symbol'];
    $qty = $row['quantity'];
    $cost = $row['cost'] * $qty;

    //if we don't have symbol under our temp store, add it
    if(!isset($tmp[$sym])){
        //add a blank string to the temp store under the symbol
        $tmp[$sym] = '';
        //start our total at 0 for this symbol
        $totals[$sym] = 0;
        //start costs variable at 0 fo rhtis symbol
        $costs[$sym] = 0;
    }

    //add the row under the table for this symbol
    $tmp[$sym] .= "<tr><td>{$sym}</td><td>{$qty}</td><td>{$cost}</td></tr>";

    //add the quantity under the symbol
    $totals[$sym] += $qty;
}

echo "<table>\n";

//second loop to do the output
foreach($totals as $sym=>$total){
    //get the total cost
    $cost = $costs[$sym];
    //echo out the subtotal row
    echo "<tr class='subtotal'><td>{$sym}</td><td>{$total}</td><td>{$cost}</td></tr>";
    //echo out the individual rows
    echo $tmp[$sym];
}

echo "</table>\n";