PHP:如何在“for each”循环中进行求和?

时间:2014-08-12 12:53:23

标签: php foreach sum

我创建了一个foreach循环,用于打印xml文件中的一些变量:

foreach ($xml->result->rowset->row as $row)
{
    echo $row["price"] . " " . $row["product"] . "</br>";
}

我想得到显示的所有“价格”的总和。我该怎么办?

5 个答案:

答案 0 :(得分:2)

只需让变量在迭代时加上这些值:

$total = 0; // start with zero
foreach ($xml->result->rowset->row as $row)
{
    $total += $row["price"]; // add price to total
    echo $row["price"] . " " . $row["product"] . "</br>";
}
echo $total; // echo out total amount

答案 1 :(得分:1)

将计数存储在变量中:

$total = 0;
foreach ($xml->result->rowset->row as $row) {
  echo $row["price"] . " " . $row["product"] . "</br>";
  $total += $row['price']; // assumed row_price is some integer
}
echo $total;

答案 2 :(得分:1)

只需将其添加到新变量中:

$sum = 0;
foreach ($xml->result->rowset->row as $row) {
  echo $row["price"] . " " . $row["product"] . "<br />";
  $sum += $row["price"];
}

echo $sum . "<br />";

答案 3 :(得分:1)

$sum = 0; 
foreach ($xml->result->rowset->row as $row)
{
    echo $row["price"] . " " . $row["product"] . "</br>";
    $sum += $row["price"] ;
}

echo $sum ; 

不是那么简单吗?

答案 4 :(得分:0)

$sum=0;
foreach ($xml->result->rowset->row as $row)
    {
        echo $row["price"] . " " . $row["product"] . "</br>";
        $sum +=$row["price"];
    }
echo $sum;

试试这段代码!!