首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将未知数量的php数组值相乘?

问如何将未知数量的php数组值相乘?
EN

Stack Overflow用户
提问于 2013-03-25 15:17:58
回答 2查看 1.2K关注 0票数 2

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

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

$quantity来自$_POST。

代码语言:javascript
复制
$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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-03-25 15:23:17

这将不起作用,请将其更改为:$total[] = $sum;

  • To获取产品数组的所有元素使用: after while
  1. $total .= $sum; array_product

即:

代码语言:javascript
复制
$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

票数 2
EN

Stack Overflow用户

发布于 2013-03-25 15:23:25

我觉得应该是

代码语言:javascript
复制
$sum = 1; 
while ($row = mysql_fetch_assoc($result)) {
    $sum = $row['item_cost'] * $sum; 
}
echo $sum;      
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15609584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档