【问题标题】:Join 2 laravel collections加入 2 个 laravel 集合
【发布时间】:2022-01-01 22:33:11
【问题描述】:

我有 2 个收藏:

$collection1 = [ 
{ name : "aaa" , score : 10 },
{ name : "bbb" , score : 20 }
];
$collection2 = [ 
{ name : "aaa" , score : 30 },
{ name : "bbb" , score : 10 }
];

我想加入他们以获得以下结果:

$collection3 = [ 
{ name : "aaa" , score : 40 },
{ name : "bbb" , score : 30 }
]

merge()union() 没有为我完成这项工作。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    组合集合,按名称分组并对分数求和。这可以通过 Laravel 中的集合来完成。请注意,group by 返回分组数据的集合。

    $collection1->concat($collection2);
    
    $collection1->groupBy('name')->map(function ($scores) {
        $score = $scores->first();
    
        $score['score'] = $scores->sum('score');
    
        return $score;
    });
    

    【讨论】:

    • 你让我看到了groupBy() 方法,我发现这个解决方案更有用:stackoverflow.com/questions/62550381/…。谢谢!
    • 那完全一样吗? :) 一组后跟一张地图,而不是对数组进行硬编码,而是建立在已经定义的数组上。
    【解决方案2】:

    可以通过laravel集合map()where()函数实现

    $collection1 = collect([
        [
            "name" => "aaa",
            "score" => 10
        ],
        [
            "name" => "bbb",
            "score" => 20
        ]
    ]);
    $collection2 = collect([
        [
            "name" => "aaa",
            "score" => 30
        ],
        [
            "name" => "bbb",
            "score" => 10
        ]
    ]);
    
    $collection3 = $collection1->map(function ($item) use ($collection2) {
            $found = $collection2->where('name', $item['name']);
            if ($found) {
                $item['score'] = $item['score'] + $found->first()['score'];
            }
            return $item;
        });
    
    dd($collection3);
    

    这是https://phpsandbox.io/n/soft-flower-ap1e-vo2xy的结果

    【讨论】:

    【解决方案3】:

    $collection = collect();$collection->merge(['col1' => $col1, 'col2' => $col2 ]); 或 $states = ['德里','泰米尔纳德邦','北方邦']; foreach ($states 作为 $state) { $data = DB::table('user')->select('user.*') ->where("user.city", $state)->where('user.status', 1)->得到(); if (!empty($data[0])) $stateUser = $stateUser->merge([$state => $data]);}

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多