Home > database >  Show genre labels from movies
Show genre labels from movies

Time:04-23

I have a structure like below, there are movies and for each movie the genres and some other info that is not relevant for the question.

The dump:

dd($moviesInformation['movies']['data']);

shows:

^ array:8 [▼
  0 => array:22 [▶]
  1 => array:22 [▼
    "id" => 75
    "name" => array:1 [▼
      "label" => "movie title"
    ]
        "genres" => array:2 [▼
          "data" => array:32 [▼
            0 => array:3 [▼
              "id" => 64
              "name" => array:1 [▼
                "label" => "Comedy"
              ]
              "on_request" => 1
            ]
            1 => array:3 [▼
              "id" => 65
              "name" => array:1 [▼
                "label" => "Action"
              ]
              "on_request" => 1
            ]
            2 => array:3 [▶]
            3 => array:3 [▶]
            4 => array:3 [▶]
            5 => array:3 [▶]
          ]
          "meta" => array:1 [▶]
        ]
     ...
      ]
      2 => array:22 [▶]
      3 => array:22 [▶]
      4 => array:22 [▶]
      5 => array:22 [▶]
      6 => array:22 [▶]
      7 => array:22 [▶]

The output should be just the unique values of all movies for genres separated by "," like for example:

Comedy, Action, ...

But I'm not understanding how to properly achieve that. Do you know how it can be?

CodePudding user response:

Your main problem is you are not treating genre like an array in your example and also missing the nested data array.

Collections will make this logic far more readable. This should give you a comma separated strings of genres.

collect(data_get($moviesInformation, 'genres.data', []))
  ->map(function ($genre) {
    return data_get($genre, 'name.label');
  })->implode(', ')

Screenshot in Tinkerwell of the output.

working example

  • Related