如何获得此 collection 的 child 值?

How can I get child value of this collection?

我有 collection 这样的:

array:13 [▼
  "id" => 1
  "sport_id" => 1
  "section_id" => 1
  "slug" => "northern-ireland-premiership"
  "name_translations" => array:2 [▶]
  "has_logo" => true
  "logo" => "https://tipsscore.com/resb/league/northern-ireland-premiership.png"
  "start_date" => "2021-08-27 18:45:00"
  "end_date" => "2022-03-26 23:59:00"
  "priority" => 0
  "host" => array:2 [▶]
  "tennis_points" => 0
  "facts" => array:6 [▶]
]

我想选择需要的值但是我无法达到child个值,例如:

"name_translations" => array:2 [▼
    "en" => "Premiership"
    "ru" => "Премьершип"
  ]

这是我的代码:

foreach($collection as $item) {
    $data[] = [
        'ext_id' => $item['id'],
        'sport_id' => $item['sport_id'],
        'section_id' => $item['section_id'],
        'slug' => $item['slug'],
        'logo' => $item['logo']
    ];
}

dd($data);

如何获得 name_translation "en" 值?

请记住包括您尝试过的方法和不适合您的方法。

您可以像访问其他任何东西一样简单地访问它$item['name_translations']['en']

foreach($collection as $item) {
        $data[] =[
            'ext_id' => $item['id'],
            'sport_id' => $item['sport_id'],
            'section_id' => $item['section_id'],
            'slug' => $item['slug'],
            'logo' => $item['logo'],
            'en' => $item['name_translations']['en']
        ];
    }
    dd($data);

假设您的集合是 Collection 的实例,映射操作将为您提供所需的数组。

$data = $collection->map(function ($item) {
    return [
        'ext_id' => $item['id'],
        'sport_id' => $item['sport_id'],
        'section_id' => $item['section_id'],
        'slug' => $item['slug'],
        'logo' => $item['logo'],
        'en' => $item['name_translations']['en']
    ];
});

使用简写闭包 (PHP >= 7.4)

$data = $collection->map(fn($item) => [
    'ext_id' => $item['id'],
    'sport_id' => $item['sport_id'],
    'section_id' => $item['section_id'],
    'slug' => $item['slug'],
    'logo' => $item['logo'],
    'en' => $item['name_translations']['en']
]);