重命名 Laravel Collection 键

Rename Laravel Collection Key

我有一套数据字典$dataDictCollection

"column_a" => "Column A",
"column_b" => "Column B",
"column_c" => "Column C",
"column_d" => "Column D",
"column_e" => "Column E",

我还有一组结果$resultCollection

[{
    "column_a" => "value 100",
    "column_b" => "value 200",
    "column_c" => "value 300",
    "column_d" => "value 400",
    "column_e" => "value 500",
},{
    "column_a" => "value 110",
    "column_b" => "value 220",
    "column_c" => "value 330",
    "column_d" => "value 440",
    "column_e" => "value 550",
}]

在结果中,我想将数据字典的值作为结果的键。例如:

"Column A" => "value 100",
"Column B" => "value 200",
"Column C" => "value 300",
"Column D" => "value 400",
"Column E" => "value 500",

请注意,我的列数很多,我无法像下面那样指定键名。

return $data['Column A'] = 'value 100';

我尝试了 mapWithKeyskeyBy 但我不知道如何 return 我想要的结果。

我试过了

return collect($resultCollection)->map(function ($result) use ($dataDictCollection) {
    return collect($dataDictCollection)->map(function ($dataDic) use ($result) {
        $name[$dataDic] = $result[$dataDic];
        return $name;
    });
});

但它 return 是这样的 :(

"column_a": {
    "Column A": "value 100"
},
"column_b": {
    "Column B": "value 200"
},

再次尝试

return collect($resultCollection)->map(function ($result) use ($dataDictCollection) {
    return collect($result)->combine($dataDictCollection);
})->values();

但它 return 是这样的,颠倒了而不是 return 完整的数据字典。

[{
    "value 100" => "Column A",
    "value 200" => "Column B",
    "value 300" => "Column C",
},{
    "value 110" => "Column A",
    "value 220" => "Column B",
    "value 330" => "Column C",
}]    

可以使用combine采集方法

$resultCollection = collect([
    "column_a" => "Column A",
    "column_b" => "Column B",
    "column_c" => "Column C",
    "column_d" => "Column D",
    "column_e" => "Column E",
])->sortKeys();

$dataDictCollection = collect([[
    "column_a" => "value 100",
    "column_b" => "value 200",
    "column_c" => "value 300",
    "column_d" => "value 400",
    "column_e" => "value 500",
], [
    "column_a" => "value 110",
    "column_b" => "value 220",
    "column_c" => "value 330",
    "column_d" => "value 440",
    "column_e" => "value 550",
]]);

$result = collect();
$dataDictCollection->each(function ($item, $key) use ($result, $resultCollection) {
    $result->push($resultCollection->combine(collect($item)->sortKeys())->all());
});

dd($result->all());