我想将Laravel集合中的一些键映射到存储在数组中的其他键。
我无法发明"这种转变的适当整齐和短暂的管道。
以下是我想要的简化示例:
$mappedKeys = [
'1' => 'One',
'2' => 'Two',
'3' => 'Three',
'4' => 'Four',
];
$data = collect([
'1' => 'I',
'2' => 'II',
'3' => 'III',
'5' => 'V',
]);
$resultCollection = $data->...
/*
* I want to receive after some manipulations
*
* [
* 'One' => 'I',
* 'Two' => 'II',
* 'Three' => 'III',
* '5' => 'V',
* ]
*/
答案 0 :(得分:3)
您始终可以在集合中使用combine()方法:
$mappedKeys = [
'1' => 'One',
'2' => 'Two',
'3' => 'Three',
'4' => 'Four',
];
$data = collect([
'1' => 'I',
'2' => 'II',
'3' => 'III',
'5' => 'V',
]);
$resultCollection = $data->keyBy(function ($item, $key) use ($mappedKeys) {
return isset($mappedKeys[$key]) ? $mappedKeys[$key] : $key;
});
希望这有帮助!
答案 1 :(得分:1)
更新的答案
$resultCollection = $data->combine($mappedKeys);