【问题标题】:Collection to associative array with specific keys [L5.2]集合到具有特定键的关联数组 [L5.2]
【发布时间】:2017-10-29 11:09:37
【问题描述】:

我有下一个收藏:

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,所以 ma​​pWithKeys() 没有实现 Collection 方法。

【问题讨论】:

    标签: laravel collections laravel-5.2


    【解决方案1】:

    你想使用函数->pluck('name_en', 'iso3166')。

    【讨论】:

    猜你喜欢
    • 2017-07-07
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    相关资源
    最近更新 更多