在 Laravel 中,可以使用 collect() 函数将数组转换为集合。

例如,将以下数组转换为集合:

$numbers = [1, 2, 3, 4, 5];

可以使用以下代码将其转换为集合:

$collection = collect($numbers);

可以使用集合中的各种方法,如 map()filter()reduce(),对集合进行操作。

$filteredCollection = $collection->filter(function ($number) {
    return $number % 2 == 0;
});

$sum = $filteredCollection->reduce(function ($carry, $number) {
    return $carry + $number;
});

echo $sum; // 输出 6
laravel 数组转成集合

原文地址: https://www.cveoy.top/t/topic/ePpB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录