我在laravel做了一个foreach后,我得到一个空的变量

问题描述 投票:1回答:2

当我真的得到3500时,我得到一个空洞的结果

 $transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())->pluck('ammount');

 $ammount = 0 ;

 foreach ($transcationhist as $p) {

    $ammount = $ammount + $p['ammount'];

 }
php laravel laravel-5 laravel-5.6
2个回答
4
投票

如果你想要总和金额,tat案例使用此代码

$ammount = Transcationhistorique::whereDate('created_at', Carbon::today())->sum('ammount');

或者你可以使用它

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())
    ->pluck('ammount');
$ammount = $transcationhist->sum();

最后,如果您想使用foreach,请使用此代码

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())
    ->get(['ammount']);

 $ammount = 0 ;

 foreach ($transcationhist as $p) {
    $ammount = $ammount + $p['ammount']; // or $p->ammount
 }

2
投票

Pluck会在你的情况下返回一个扁平数组,使用它:

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())->pluck('ammount');

 $ammount = 0 ;

 foreach ($transcationhist as $p) {

    $ammount += $p;

 }
© www.soinside.com 2019 - 2024. All rights reserved.