Search code examples
laravellaravel-collection

Rename Laravel Collection Key


I have a set of data dictionary $dataDictCollection

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

I have another set of result $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",
}]

In the result, I'd like to have the data dictionary's value as the result's key. For example:

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

Do note that my number of columns are A LOT, I could not specify the key name like below.

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

I tried mapWithKeys, keyBy but I don't know how to return my desire result.

I tried

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

But it returns this :(

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

Another attempt

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

but it returns like this, reversed and not returning the full data dictionary.

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

Solution

  • You can use the combine method of collection

    $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());