2017-02-01 94 views
5

我一直在嘗試使用laravel的集合函數創建一個名爲mapWithKeys的數組,但我無法實現我所需要的。Laravel集合mapWithKeys

這裏是我的代碼,

$years = range(1900, date('Y')); 

return collect($years)->mapWithKeys(function($value){ 
    return [$value => $value]; 
})->all(); 

預期結果

Array 
(
    [1900] => 1900 
    [1901] => 1901 
    [1902] => 1902 
    .... 
    [2017] => 2017 
) 

但我得到的是

Array 
(
    [0] => 1900 
    [1] => 1901 
    [2] => 1902 
    ... 
    [117] => 2017 
) 

回答

2

我測試過此代碼,它完美的作品:

$years = range(1900, date('Y')); 
return collect($years)->map(function($i) { 
    return ['year' => $i]; 
}, $years)->pluck('year', 'year'); 
+0

陣列 ( [0] =>數組 ( [1900] => 1900 ) )我得到的值是這樣的。 –

+0

我更新了代碼。 –

+0

謝謝。有用。但我想知道爲什麼它不與mapWithKeys函數一起工作。如果我將[$ value => $ value]替換爲['s'。$ value => $ value],它就可以工作。我認爲問題是關鍵和價值是相同的。 –