首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在PHP Laravel中对子数组项进行分组和求和

在PHP Laravel中,你可以使用集合(Collection)类来对子数组项进行分组和求和。

首先,你需要使用groupBy()方法将子数组按照指定的键进行分组。该方法接受一个闭包函数作为参数,你可以在闭包函数中返回需要进行分组的键。

代码语言:txt
复制
$collection = collect([
    ['name' => 'John', 'score' => 50, 'subject' => 'Math'],
    ['name' => 'Jane', 'score' => 70, 'subject' => 'Math'],
    ['name' => 'John', 'score' => 80, 'subject' => 'Science'],
    ['name' => 'Jane', 'score' => 60, 'subject' => 'Science'],
]);

$grouped = $collection->groupBy(function ($item) {
    return $item['name'];
});

上述代码将根据数组中name键的值对子数组进行分组,得到以下结果:

代码语言:txt
复制
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [John] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => Array
                                (
                                    [name] => John
                                    [score] => 50
                                    [subject] => Math
                                )

                            [1] => Array
                                (
                                    [name] => John
                                    [score] => 80
                                    [subject] => Science
                                )

                        )

                )

            [Jane] => Illuminate\Support\Collection Object
                (
                    [items:protected] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Jane
                                    [score] => 70
                                    [subject] => Math
                                )

                            [1] => Array
                                (
                                    [name] => Jane
                                    [score] => 60
                                    [subject] => Science
                                )

                        )

                )

        )

)

接下来,你可以使用map()方法对分组后的子数组进行遍历,并使用sum()方法求和。这里的sum()方法可以接受一个闭包函数作为参数,在闭包函数中返回需要进行求和的键。

代码语言:txt
复制
$sums = $grouped->map(function ($items) {
    return $items->sum('score');
});

上述代码将对每个分组的子数组中的score键进行求和,得到以下结果:

代码语言:txt
复制
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [John] => 130
            [Jane] => 130
        )

)

现在,$sums变量包含了每个分组的子数组的求和结果。

这是如何在PHP Laravel中对子数组项进行分组和求和的简单示例。在实际应用中,你可以根据需要进行更复杂的操作和处理。如果想了解更多关于PHP Laravel的相关知识,可以参考腾讯云的Laravel云托管产品。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券