Nishant Sah
Nishant Sah

Reputation: 151

How to use collection to merge arrays in laravel so that one becomes the key?

I have an array of arrays like so:

array (
array("Delhi", 22, "The capital of India"), 
array("Varanasi", 23, "Oldest Living City"), 
array ("Moscow", 24, "Capital of Russia"), 
array ("Konya", 25, "The city of Rumi"), 
array("Salzburg", 26, "The city of Mozart")
);

I want to make an associated collection like so:

['city' => "Delhi",
'id' => 22,
'description' => "The capital of India"
], 
['city' => "Varanasi",
'id' => 23,
'description' => "Oldest Living City"
], 
['city' => "Moscow",
'id' => 24,
'description' => "Captial of Russia"
]

This can be done by passing the data through a loop but is there anything in the collection that can get this done?

Upvotes: 0

Views: 771

Answers (1)

Tuim
Tuim

Reputation: 2511

One could use array_combine or combine from Laravel

$collection = array(
    array("Delhi", 22, "The capital of India"),
    array("Varanasi", 23, "Oldest Living City"),
    array("Moscow", 24, "Capital of Russia"),
    array("Konya", 25, "The city of Rumi"),
    array("Salzburg", 26, "The city of Mozart")
);


array_map(function($array){
    return array_combine(['city', 'id', 'description'], $array);
}, $collection);

//Or with a Laravel collection
collect($collection)->map(function($arr){
    return array_combine(['city', 'id', 'description'], $arr);
});

Upvotes: 3

Related Questions