LaravelCollection。将一个键映射到另一个键

Laravel Collection. Map one keys to other

我想将 Laravel collection 中的一些键映射到存储在数组中的其他键。

我无法"invent"为这样的转换提供合适的简洁短管道。

这是我想要的简化示例:

$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',
 * ]
 */

更新答案

$resultCollection = $data->combine($mappedKeys);

您始终可以对集合使用 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;
});