laravel 集合:如何组合两个不同类型的数组并分配键和新项

laravel collection : How to combine two different type array and asign key and new item

我有 2 个这样的数组

$packers_id = [
[984538,{"PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6"}],
[984538,{"PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6"}],
[984543,{"PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6"}],
[984543,{"PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6"}]
]

如何使用 laravel 收集方法将数组更改为这样并添加一些项目

$packers_id = [
{"Arr_ID":"984538","PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6","changeby":"me"},
{"Arr_ID":"984538","PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6","changeby":"me"},
{"Arr_ID":"984543","PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6","changeby":"me"},
{"Arr_ID":"984543","PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6","changeby":"me"}
]

我可以使用 foreach 来完成,但我不想要它,因为我看到 laravel 集合方法中有 map 方法和其他方法。 我的目标是获得干净的代码和最快的时间。

也许我们可以根据laravel文档使用mapToGroup函数。

$collection = collect([
[984538,{"PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6"}],
[984538,{"PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6"}],
[984543,{"PartCode":"packs701620010","Qty":"13","ID":"1398163","Date":"2020\/08\/08 15:4:6"}],
[984543,{"PartCode":"packs701620020","Qty":"1","ID":"1398164","Date":"2020\/08\/08 15:4:6"}]
]);

然后我们可以 mapToGroups 我们新制作的集合。

    $grouped = $collection->mapToGroups(function ($item, $key) {
        return [
           $item[0] => $item['ID'],
           $item[1]["PartCode"] => $item["PartCode"],
           $item[1]["Qty"] => $item["Qty"],
           ....
        ];
    });

注意可能导致新错误的重复 ID。