vendredi 27 septembre 2019

PHP - use declared var from foreach in next iteration

I would ask for help with foreach and using vars. There are several conditions in the loop. If value from array is equal to something then happened something and so on. I need to save something to variable and then use it in second iteration of foreach. Then I use array $totals in frontend. I would like to keep order - so first in $totals should be sub_total, then tax and then total.

I tried also define $difference and $tax before foreach but It is getting resetted at every iteration. Now I have done it by using session but I am not sure if it's correct and I would like to do it without session. I hope you uderstand.

Could you help me please? Thank you.

EXAMPLE:

Array ( [0] => Array(
              [code] => sub_total 
              [value] => 3140.5000) 
        [1] => Array ( 
              [code] => tax 
              [value] => 680.2950) 
        [2] => Array ( 
              [code] => total 
              [value] => 3919.7950) 
       ) 
  $totals = array();
foreach($array as $key => $value) {
  if (!in_array($value['code'], array('sub_total', 'tax', 'total')){
       //do something, not important, just showing structure of my code
  } else {
    if($value['code'] == 'total') {
        $text = $value['total'];
      if(round($value['value']) > $value['value']) {
        $difference = round($value['value']) - $value['value'];
        $tax = ($difference*($tax_rate/(100+$tax_rate)));
      }
    }
    if($value['code' == 'tax') {
     $text= $value['value'] + $tax;
     echo $tax; //shows nothing
     echo $text; //shows only 680.2950 ($value['value'] without $tax)
    }
   echo $tax; // Shows $tax correctly
 }
    $totals[] = array(

         'code'  => $value['code'],

         'text'  => $text,

    ); }

Aucun commentaire:

Enregistrer un commentaire