如何将集合合并到 Laravel 中的特定列中

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

我有 3 个不同对象的集合。我需要根据共享值将这3个集合聚合为1(这里共享值是

id
)。 我的意思是:

$names = {"id":1, "name":"John"};
$ages = {"id":1, "age":20};
$address = "{"id":1, "address":"222"};
  .......
 .........

如果我返回

return $names->merge($ages)->merge($address)
,它会显示如下:

[
  {"id":1, "name":"John"},
  {"id":1, "age":20},
  {"id":1, "address":"222"},
  {"id":2, "name":"Jim"},
  {"id":2, "age":30},
  {"id":2, "address":"333"},
]

我想这样回报我:

[
   {"id":1, "name":"John", "age":20 , "address":"222"},
   {"id":2, "name":"Jim", "age":30 , "address":"333"}
 ]
laravel collections
2个回答
0
投票

这是我的解决方案:

$items = [
  {"id":1, "name":"John"},
  {"id":1, "age":20},
  {"id":1, "address":"222"},
  {"id":2, "name":"Jim"},
  {"id":2, "age":30},
  {"id":2, "address":"333"},
];

$items = collect($items)->groupBy('id');
$result = [];
foreach ($items as $values) {
  $temp = [];
  foreach ($values as $value) {
    $temp = array_merge($temp, $value);
  }
  $result[] = $temp;
}

dd($result);

0
投票

对于完全 Laravel 解决方案,按

id
进行分组,然后迭代这些组并展平关联数据,然后重新索引集合并将其转换为 json。

代码:(PHPize演示

echo collect($items)
     ->groupBy('id')
     ->map(
         fn($group) => $group->flatMap(
             fn($items) => $items
         )
     )
     ->values()
     ->toJson();

要仅循环有效负载一次,请使用

reduce()
(PHPize Demo)

echo json_encode(
    collect($items)
        ->reduce(function ($result, $item) {
            static $ref = [];
            if (!isset($ref[$item['id']])) {
                $ref[$item['id']] = $item;
                $result[] =& $ref[$item['id']];
            } else {
                $ref[$item['id']] += $item;
            }
            return $result;
        },
        []
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.