集合中的乘积值

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

大家好,我有类似的东西,我想乘以每个对象的“数字”。例如2(第一个对象编号)x3(第二个对象编号)= 6(答案应该为6)有人知道怎么做吗?数组并不总是相同的。这里有2个对象,但可以更改。

[{"id":7,"date":"2020-03-14","number":2},{"id":20,"date":"2020-03-15","number":3}]  

更新后的答案(有效)

                     foreach ($studentDetail as $student){
                     $number = calendar::where('student_id','=',$student['id'])
                            ->where('date','>=',$jsonData->checkin)
                            ->where('date','<',$jsonData->checkout)
                            ->get();
                        Log::info($number );
                        $multiplied= $number ->reduce(function ($carry, $item) {
                             return $carry * $item->number;
                        }, 1);
                        Log::info($multiplied);
                        }

php arrays laravel multiplying
1个回答
1
投票

reduce方法将集合简化为单个值,并传递每次迭代的结果进入后续迭代

$multiplied= $collection->reduce(function ($carry, $item) { return $carry * $item->number; }, 1);
© www.soinside.com 2019 - 2024. All rights reserved.