如何使用collection合并laravel中的数组,使一个成为key?
How to use collection to merge arrays in laravel so that one becomes the key?
我有一个这样的数组:
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")
);
我想像这样创建一个关联集合:
['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"
]
这可以通过循环传递数据来完成,但集合中是否有任何东西可以完成此操作?
可以使用 array_combine 或结合 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);
});
我有一个这样的数组:
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")
);
我想像这样创建一个关联集合:
['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"
]
这可以通过循环传递数据来完成,但集合中是否有任何东西可以完成此操作?
可以使用 array_combine 或结合 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);
});