2017-05-29 66 views
1

我的下一個集合數組:收集到關聯特定鍵[15.2]

Collection {#356 ▼ 
    #items: array:31 [▼ 
    0 => {#359 ▼ 
     +"id": 17 
     +"zone_id": 2 
     +"name_de": "Österreich" 
     +"name_en": "Austria" 
     +"name_iso": "AUSTRIA" 
     +"tld": "at" 
     +"iso3166": "AT" 
     +"phone": 43 
     +"vat_regex": "/^U[0-9]{8}$/" 
     +"shop_id": 17 
     +"country_id": 165 
    } 
    1 => {#360 ▼ 
     +"id": 2 
     +"zone_id": 2 
     +"name_de": "Belgien" 
     +"name_en": "Belgium" 
     +"name_iso": "BELGIUM" 
     +"tld": "be" 
     +"iso3166": "BE" 
     +"phone": 32 
     +"vat_regex": "/^[01][0-9]{9}$/" 
     +"shop_id": 17 
     +"country_id": 25 
    }] 
} 

我想接下來的結果作爲關聯數組:

[ 
    "AT" => "Austria", 
    "BE" => "Belgium" 
] 

我嘗試使用做到這一點:

$keyed = $countries->map(function ($item) { 
    return [$item->iso3166 => $item->name_en]; 
}); 

但我發現了:

Collection {#357 ▼ 
    #items: array:31 [▼ 
    0 => array:1 [▼ 
     "AT" => "Austria" 
    ] 
    1 => array:1 [▼ 
     "BE" => "Belgium" 
    ] 
    ] 
} 

我在做什麼錯了,或者我該如何實現關聯數組?

注意:我正在使用Laravel 5.2所以mapWithKeys()收集方法未實現。

回答

2

您想使用功能->pluck('name_en', 'iso3166')

+0

因爲這樣,我不知道拔毛方法。謝謝。 – Troyer

+1

@Troyer是的,收集非常整潔;還有一本關於收藏的免費書籍https://leanpub.com/laravelcollectionsunraveled玩得開心! :) – Kyslik