Search code examples
phpmathforeachsmarty

Smarty Math Function Foreach Loop


I am using smarty templating engine and am encountering a math issue. I am trying to create a total amount (sum) based on amounts in the array. (Normally I would do this at the server level, but do to the way that I create the array, dont think that is possible.) I am merging two arrays into one, but each array shares an 'Amount' which I am trying to determine the 'Total Amount'

Here are the steps I am taking two arrays pushing into one array:

foreach ($data_main1 as $transaction_main1) {
    $json_decoded = json_decode($transaction_main1['NewObject']);
    $amount = $transaction_main1['Amount']; 
    $mycart1[] = array('ParentType' => $ParentType, 'Amount' => $amount);
    }

$mycart2=array();
foreach ($data_main2 as $transaction_main2) {
    $json_decoded = json_decode($transaction_main2['NewObject']);
    $amount = $transaction_main2['Amount'];
    $mycart2[] = array('ParentType' => $ParentType, 'Amount' => $amount);
    }


$mycart =  array_merge((array)$mycart1, (array)$mycart2);
$smarty->assign('cart', $mycart);

Here is my Smarty along with the math equation that does not show the value:

{assign var=last value=$cart[cart].Amount+1}

(I am certainly open to the idea of creating a total amount on the array_merge, just unsure how to do that, or even if it is possible)


Solution

  • Do you know about the {math} Smarty bult-in function?

    {math equation="x + 1" x=$cart[cart].Amount}
    

    Let me know if it works.