Search code examples
smarty

foreach from=$results item="entry" name=status


I am trying to add up the value of a specific ({$entry.zip}) field within an array but I can't seem to figure it out, don't particularly want to go through a loop if at all possible.

{foreach from=$results item="entry" name=status} 
    {$entry.id} {$entry.id} {$entry.id} {$entry.zip}
{/foreach}

{$entry.zip} produces various numbers, and I would like to add them up to provide me with a running total. Is it possible?

Cheers, Jason.


Solution

  • Adapting your example this should be rather straight forward.

    {assign var='mysum' value=0}
    {foreach from=$results item="entry" name=status} 
        {assign var='mysum' value=$mysum+$entry.zip}
        {$entry.id} {$entry.id} {$entry.id} {$entry.zip} {$mysum}
    {/foreach}
    

    However, for the sake of separating the application logic from the view layer, which Smarty is usually for, I'd put that somewhere in your php code, maybe even in the array itself which results into $results.