Php laravel控制器中foreach循环的和值

Php laravel控制器中foreach循环的和值,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,如何对数据求和 在获得控制器Laravel的先前计算后 private$nn; 公共功能项目(代码项目) { $countdata=计数($listdata); $countdata=15/$countdata; foreach($listdata作为$obj){ $this->nn=$obj->percent*$countdata/100; $this->nn+=($obj->persen); } dd($this->nn); } 如何做到这一点?您可以使用或。由于这是一个拉威尔问题,我将使

如何对数据求和 在获得控制器Laravel的先前计算后

private$nn;
公共功能项目(代码项目)
{
$countdata=计数($listdata);
$countdata=15/$countdata;
foreach($listdata作为$obj){
$this->nn=$obj->percent*$countdata/100;
$this->nn+=($obj->persen);
}
dd($this->nn);
}
如何做到这一点?

您可以使用或。由于这是一个拉威尔问题,我将使用
reduce()

$collection=collect($listdata);
$percentage=0.15*$collection->count();
$sum=$collection->reduce(函数($carry,$item)使用($percentage){
返回$carry+($item->percent*$percentage);
}, 0);
dd(金额);

如果您在保存数据后返回,请使用此方法,从现有列中提取数据并将其显示在刀片文件中

//initialize percentage if constant for every record on DB
//if not constant pull($Percentage) from DB as column as shown below.

//$x; $y are specific columns found in table in DB.

// replace mathematical signs where necessary.

// if needed as per row mask the formulae in your for each loop

$percentage = ''  

        $total = array_sum(array_map(function($x, $y) { return $x * $y; },
                $carry, $item)) * ($percentage);


欢迎来到StackOverflow!请举例说明
$listdata
包含的数据类型。另外,请举例说明您的预期结果。话虽如此,在foreach循环中覆盖
$this->nn=…
。如果你把这条线放在前面,它可能会起作用。请尝试并提供示例,以便更容易进一步帮助您。