2

我有一个数据库输出循环。

我需要将值相乘$total,将结果分配给另一个变量并输出。我该怎么做?

$quantity来自$_POST.

$items = implode(",",array_keys($_POST));

mysql_query('SET NAMES utf8');
$query = 'SELECT * FROM
    items
WHERE
    item_id IN (' . $items . ')';

$result = mysql_query($query, $db) or die (mysql_error($db));

echo ' 

<table id="items">
<tr class="head">
    <td>Name</td>
    <td>Cost</td>
    <td>Quantity</td>
    <td>Subtotal</td>
</tr>

';
$total = array ();  
while ($row = mysql_fetch_assoc($result)) {
echo '<tr class="targetfields">';
echo '<td>' . $row['item_name'] . '</td>

<td>' . $row['item_cost'];
//Getting item id
foreach ($_POST as $itemid=>$quantity)
{
//Displayin' quantity
if ($itemid == $row['item_id']){
    echo '</td><td><input name="' . $row['item_id'] . '" class="input-small" size="2" maxlength="2" type="text" value="';
    echo "{$quantity}";
    echo '" readonly></td>
    <td>'; $sum = ($row['item_cost'] * $quantity); echo $sum;
    echo '</td>';

    $total.= $sum;

}


}
        echo '</tr>';
}

?>  <tr>
<td class="sum" colspan="4">    Total: 
<?php 



?> </td>
</tr>
</table>
4

2 回答 2

2
  1. $total .= $sum;这将不起作用将其更改为:$total[] = $sum;
  2. 要获得产品的所有数组元素,请$total使用:while 循环之后array_product

IE :

$items = implode(",",array_keys($_POST));

mysql_query('SET NAMES utf8');
$query = 'SELECT * FROM
    items
WHERE
    item_id IN (' . $items . ')';

$result = mysql_query($query, $db) or die (mysql_error($db));
$total = array ();  
while ($row = mysql_fetch_assoc($result)) {

$sum = ($row['item_cost'] * $quantity); echo $sum;      
$total[] = $sum;

}

echo array_product($total);

参考: http: //php.net/manual/en/function.array-product.php

于 2013-03-25T07:23:17.403 回答
2

我认为应该是

$sum = 1; 
while ($row = mysql_fetch_assoc($result)) {
    $sum = $row['item_cost'] * $sum; 
}
echo $sum;      
于 2013-03-25T07:23:25.413 回答