【问题标题】:Sum Values in a foreach loop in laravel controllerlaravel控制器中foreach循环中的总和值
【发布时间】:2021-08-01 10:53:02
【问题描述】:

如何对数据求和 在控制器 Laravel 上得到之前的计算后

private $nn;

public function detailproject($code_project)
{
    $countdata = count($listdata);
    $countdata = 15 / $countdata;

    foreach ($listdata as $obj ) {
        $this->nn = $obj->percent * $countdata / 100;
        $this->nn +=($obj->persen);
    }
    
    dd($this->nn);
}

如何做到这一点?

【问题讨论】:

  • 欢迎来到 StackOverflow!请举例说明$listdata 包含的数据类型。还要展示一个示例,说明您的预期结果是什么。话虽如此,您在 foreach 循环中覆盖 $this->nn = ...。如果您将该行放在 foreach 之前,它可能会起作用。请尝试提供示例,以便更轻松地为您提供进一步的帮助。

标签: php laravel laravel-5 eloquent


【解决方案1】:

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

//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);

【讨论】:

    【解决方案2】:

    您可以使用array_reduce()reduce()。既然是 Laravel 的问题,那我就用reduce()

    $collection = collect($listdata);
    $percentage = 0.15 * $collection->count();
    
    $sum = $collection->reduce(function ($carry, $item) use ($percentage) {
        return $carry + ($item->percent * $percentage);
    }, 0);
    
    dd($sum);
    

    【讨论】:

      猜你喜欢
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多