我的加法有一个问题:所以我有这样的代码:
$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;所以我想把最后一个值保存在total_montant中,而不是工作,我不理解why...Can,你能帮我吗?提前进行Thx
发布于 2016-02-10 00:44:48
您还应执行以下操作:
$total = $total + $history['montant'];否则,您不需要添加任何内容(从$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'];
$total = $total + $history['montant'];
$aHistory[] = $aHistoryFilter;
}发布于 2016-02-10 00:45:36
将您的代码更新为:
$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 ;因为在您的代码中,您对$total执行$history['montant']操作,但没有将结果赋值给$total
发布于 2016-02-10 00:46:55
试试这个:
$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;https://stackoverflow.com/questions/35297425
复制相似问题