You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何合并两个集合生成笛卡尔积组合?

在Laravel中生成两个带键集合的笛卡尔积组合

嗨,这个需求其实用Laravel集合的原生方法就能轻松实现,我给你两种实用的方案,都能得到你想要的组合结构:

方案一:使用map+crossJoin+map组合

先把每个集合的元素转换为单键值对的数组,再生成笛卡尔积,最后合并每组的键值对:

$sizes = collect([10 => 'xl', 11 => 'xxl', 12 => 'xxxl']);
$colors = collect([20 => 'red', 21 => 'green', 22 => 'blue']);

// 将每个元素转为单键值对数组,保留原键
$sizePairs = $sizes->map(fn($val, $key) => [$key => $val]);
$colorPairs = $colors->map(fn($val, $key) => [$key => $val]);

// 生成笛卡尔积并合并每组的两个数组
$result = $sizePairs->crossJoin($colorPairs)->map(fn($pair) => $pair[0] + $pair[1]);

方案二:使用flatMap+map嵌套(更简洁)

通过外层遍历尺寸集合,内层遍历颜色集合,直接生成组合并平铺为最终集合:

$sizes = collect([10 => 'xl', 11 => 'xxl', 12 => 'xxxl']);
$colors = collect([20 => 'red', 21 => 'green', 22 => 'blue']);

$result = $sizes->flatMap(function ($sizeVal, $sizeKey) use ($colors) {
    return $colors->map(function ($colorVal, $colorKey) use ($sizeKey, $sizeVal) {
        return [
            $sizeKey => $sizeVal,
            $colorKey => $colorVal
        ];
    });
});

验证结果

两种方案生成的$result都会是你需要的结构:

collect([
    [10 => 'xl', 20 => 'red'],
    [10 => 'xl', 21 => 'green'],
    [10 => 'xl', 22 => 'blue'],
    [11 => 'xxl', 20 => 'red'],
    [11 => 'xxl', 21 => 'green'],
    [11 => 'xxl', 22 => 'blue'],
    [12 => 'xxxl', 20 => 'red'],
    [12 => 'xxxl', 21 => 'green'],
    [12 => 'xxxl', 22 => 'blue'],
]);

内容的提问来源于stack exchange,提问作者Ahmad Badpey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:22:07