简体   繁体   English

显示foreach循环的总和

[英]Displaying the sum of a foreach loop

I have a table like this: id | item_name | price 我有一个这样的表: id | item_name | price id | item_name | price

I have a loop that displays all items with the grand total at the bottom. 我有一个循环,在底部显示总计的所有项目。

$total_price = 0;

foreach($items as $item)
{
    echo $item->item_name;
    echo $item->price;

    $total_price += $item->price;
}

echo $total_price;

However, what I need is to display the $total_price at the TOP of the page, before I loop through all the items. 但是,我需要在循环浏览所有项目之前在页面的顶部显示$total_price

Is it better to loop through the foreach again at the top of the page to calculate the total price, or should I be making a separate database call that only returns the total price? 还是最好在页面顶部再次foreach以计算总价,还是我应该做一个单独的数据库调用来仅返回总价?

It's simple and fast decision 简单快捷的决定

$total_price = 0;
$print = '';
foreach($items as $item)
{
    $print .= $item->item_name;
    $print .= $item->price;

    $total_price += $item->price;
}

echo $total_price;
echo $print;

If you can get sum from SQL base it will be more best solution. 如果可以从SQL库中获取总和,那将是更好的解决方案。 In MySQL use function SUM() 在MySQL中使用函数SUM()

Example: 例:

SELECT SUM(price) AS total FROM ...

This is one of the reasons why you should never mix php code and direct output. 这就是为什么您永远不要混用php代码和直接输出的原因之一。 I would suggest you look into one of the template engines for php. 我建议您研究一下php的模板引擎之一。

Unless you are writing php-cli do all the operations before you start to output. 除非您正在编写php-cli,否则请在开始输出之前执行所有操作。 This will increase the flexibility of your code a lot. 这将大大增加代码的灵活性。

Smarty is one of my favourite tempelate engines, easy to setup and with powerfull features, but that's my opinion. Smarty是我最喜欢的模板引擎之一,易于设置且功能强大,但这是我的看法。

也许您需要像这样使用MySQL查询:

SELECT SUM(price) FROM your_table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM