Laravel - 如何将多个阵列收集到单个阵列

时间:2017-11-23 09:18:45

标签: php laravel collections

我已经创建了这样的集合:

Collection {#651 ▼
  #items: array:3 [▼
    0 => array:3 [▼
      "orderId" => "402457"
      "orderCreated" => DateTime {#656 ▶}
      "foods" => array:2 [▶]
    ]
    1 => array:3 [▼
      "orderId" => "402457"
      "orderCreated" => DateTime {#661 ▶}
      "foods" => array:2 [▶]
    ]
    2 => array:3 [▼
      "orderId" => "402457"
      "orderCreated" => DateTime {#665 ▶}
      "foods" => array:2 [▶]
    ]
  ]
}

我要求实现这样的集合(使用Laravel集合):

Collection {#651 ▼
  #items: array:3 [▼
    0 => array:3 [▼
      "orderId" => "402457"
      "orderCreated" => DateTime {#656 ▶}
      "foods" => array:6 [▶]
    ]

  ]
}

因为orderId和orderCreated在数组中都是相同的。我需要制作单个数组,收集orderId和orderCreated与所有食物。 有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以从第一个数据中获取数据,然后组合所有食物。例如:

$new = collect([
    'orderId' => $old->first()->orderId,
    'orderCreated' => $old->first()->orderCreated,
    'foods' => $old->pluck('foods')->flatten(1),
]);

确切的实现将取决于您如何构建初始集合。