Rodrigo Bogdanowicz
Rodrigo Bogdanowicz

Reputation: 71

Smarty math foreach sum

How to sum all values off foreach?

My code:

 {foreach from=$tasks key=tasknum item=task name=foo}
   <p>{$task.porcent}</p>
   {assign var="quant" value="`$smarty.foreach.foo.total`"}
 {/foreach}

 {$quant}

Objective:

Get the total number of percentage. Sum all {$task.porcent} of foreach and divide by the amount of foreach {$quant}.

With sum: {$sum_all_foreach / $quant}

Result: Percentage total

Upvotes: 1

Views: 5336

Answers (1)

pajaja
pajaja

Reputation: 2202

You can add them inside your foreach loop and divide it by {$tasks|@count} or $smarty.foreach.foo.total afterwards:

{foreach from=$tasks key=tasknum item=task name=foo}
   <p>{$task.porcent}</p>
   {assign var="sum_all_foreach" value=$sum_all_foreach+$task.percent}
{/foreach}
{assign var="result" value=$sum_all_foreach/$smarty.foreach.foo.total}

Or you can do all this in PHP when making the array.

Upvotes: 4

Related Questions