Laravel,总结foreach

时间:2018-12-18 07:49:43

标签: php laravel foreach sum totals

foreach($group as $key=>$value)
{
    echo $key. " = " .$value. "<br>";
}

例如

For example:

doc1 = 8

doc2 = 7

doc3 = 1

doc4 = 5

我想显示doc1 + doc2并求和为TOTAL1,

然后将TOTAL1 + doc3总计为TOTAL2,

然后将TOTAL2 + doc4总计为TOTAL3

如何在刀片中显示它?谢谢你对我的帮助

1 个答案:

答案 0 :(得分:2)

尝试一下

$group = [
    'doc1' => 8,
    'doc2' => 7,
    'doc3' => 1,
    'doc4' => 5
];

$totals = [];
$total = array_shift($group);
foreach(array_values($group) as $index => $value)
{
    $total += $value;
    $totals['total' . ($index + 1)] = $total;
};
dd($totals);

结果是

array:3 [▼
  "total1" => 15
  "total2" => 16
  "total3" => 21
]