合并laravel中包含键的数组



我有两个数组,我想合并它们。(我可以合并它们),但我也需要在合并结果中包含它们的唯一键,这部分我无法实现。

sample

$prices = [
['112802' => "500000"],
['113041' => "1000000"],
];
$notes = [
['112802' => "note 2"],
['113041' => "note 1"],
];
$collection = collect($prices);
$zipped = $collection->zip($notes);
$zipped->toArray();

唯一密钥为112802113041

当我合并数组时,我得到的是这个

[
[
"1000000",
"note 1"
],
[
"500000",
"note 2"
]
]

我要找的是这样的:

[
[
"id" => "112802",
"price" => "500000",
"note" => "note 2",
],
[
"id" => "113041",
"price" => "1000000",
"note" => "note 1",
]
}]

任何建议吗?

对您提供的数据执行您想要的操作。

注意,只有当你的两个数组大小相同,键的顺序相同时,它才会起作用。

如果这个数据来自数据库,它很可能已经以您实际想要的格式产生,而不是不得不摆弄数据后获取。

$prices = [
['112802' => "500000"],
['113041' => "1000000"],
];
$notes = [
['112802' => "note 2"],
['113041' => "note 1"],
];
$new = [];
foreach ($prices as $i=>$pr){
$k = key($pr);
$new[] = [  'id' => $k, 
'price' => $pr[$k], 
'note' => $notes[$i][$k] ];
}
print_r($new);

结果

Array
(
[0] => Array (
[id] => 112802
[price] => 500000
[note] => note 2
)
[1] => Array (
[id] => 113041
[price] => 1000000
[note] => note 1
)
)

这里是使用Laravel的一些Collection方法的另一个解决方案。
它不是最优雅的,但它可以成为你的一个起点。

$prices = collect([
['112802' => "500000"],
['113041' => "1000000"],
])->mapWithKeys(function($item) {
// This assumes that the key will always be the ID and the first element is the price.
// Everythng else for each element will be ignored.
$id = array_keys($item)[0];
return [$id => ["id" => $id, "price" => reset($item)]];
});
$notes = collect([
['112802' => "note 2"],
['113041' => "note 1"],
])->mapWithKeys(function($item) {
$id = array_keys($item)[0];
return [$id => ["id" => $id, "note" => reset($item)]];
});
$result = $prices->zip($notes)->map(function ($item) {
// Feel free to call `toArray()` here if you don't want a Collection.
return collect($item)->mapWithKeys(function ($a) { return $a; });
});

下面是$result(使用dd()调用)。

IlluminateSupportCollection {#1886 ▼
#items: array:2 [▼
0 => IlluminateSupportCollection {#1888 ▼
#items: array:3 [▼
"id" => 112802
"price" => "500000"
"note" => "note 2"
]
}
1 => IlluminateSupportCollection {#1889 ▼
#items: array:3 [▼
"id" => 113041
"price" => "1000000"
"note" => "note 1"
]
}
]
}

这是通过提取ID来实现的,这样zip就可以加入那里,但是然后我们需要对$result中的mapmapWithKeys进行一点hack。
这只是因为否则$result中的每个元素仍然会有两个单独的$prices$notes数组。

最新更新