2

我想将 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',
 * ]
 */
4

2 回答 2

4

您始终可以在集合上使用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;
});
于 2017-09-07T12:49:43.750 回答
1

更新的答案

$resultCollection = $data->combine($mappedKeys);
于 2017-09-07T12:47:08.037 回答