2016-02-09 1 views
1

J'ai un problème avec mon plus: J'ai donc ce code:Faire une adittion en php

   $total = 0; 
       foreach(getHistory($this->id) as $history){ 
        $aHistoryFilter['date']     = $history['date']; 
        $aHistoryFilter['ls']     = $history['ls']); 
        $aHistoryFilter['montant']    = $history['montant']; 
        $aHistoryFilter['total_montant']  = $total+$history['montant']; 
        $aHistory[] = $aHistoryFilter; 

       } 
       return $aHistory; 

Je veux enregistrer dans total_montant la dernière valeur, mais ne fonctionne pas et je ne comprends pas pourquoi ... Pouvez-vous m'aider s'il vous plaît? Thx à l'avance

+0

Essayez de mettre $ aHistory [] = $ aHistoryFilter; Avant le $ aHistoryFilter ['date'] –

+0

vous ne mettez jamais à jour '$ total', donc vous faites' total_montant = 0 + montant', ce qui revient à 'total_montant = montant' –

Répondre

2

Vous devez également faire:

$total = $total + $history['montant']; 

sinon vous ne pas ajouter quoi que ce soit (depuis $total=0;)

Ainsi, vous obtenez:

  foreach(getHistory($this->id) as $history){ 
       $aHistoryFilter['date']     = $history['date']; 
       $aHistoryFilter['ls']     = $history['ls']); 
       $aHistoryFilter['montant']    = $history['montant']; 
       $aHistoryFilter['total_montant']  = $total+$history['montant']; 
       $total = $total + $history['montant']; 
       $aHistory[] = $aHistoryFilter; 

      } 
2

mise à jour que votre code soit:

$total = 0; 
foreach(getHistory($this->id) as $history){ 
$aHistoryFilter['date']     = $history['date']; 
$aHistoryFilter['ls']     = $history['ls']); 
$aHistoryFilter['montant']    = $history['montant']; 
$total  = $total+$history['montant']; 
$aHistory[] = $aHistoryFilter; 

} 
$aHistoryFilter['total_montant'] = $total ; 

parce que dans votre code $history['montant']-$total mais vous n'avez pas affecté le résultat à $total

+0

Vous êtes en retard de quelques secondes; –

+0

@BasvanStein il n'y a pas de problème. Je vais vous voter –

+0

laissez-moi retourner la faveur, après tous les grands esprits se ressemblent. –

0

Essayez ceci:

  $total = 0; 
      foreach(getHistory($this->id) as $history){ 
       $aHistoryFilter['date']     = $history['date']; 
       $aHistoryFilter['ls']     = $history['ls']); 
       $aHistoryFilter['montant']    = $history['montant']; 

       // this adds the $history['montant'] to the $total 
       $total         += $history['montant']; 
       // this adds the $total to your variable 
       $aHistoryFilter['total_montant']  = $total; 

       $aHistory[] = $aHistoryFilter; 

      } 
      return $aHistory;