Home > database >  how to do a foreach loop values in a multidimensional array PHP
how to do a foreach loop values in a multidimensional array PHP

Time:04-18

I'm working with Spotify API and I want to do a foreach loop for only the values in ['tracks'][0]["album"]["images"][2]['url']

How can I go about this?

I tried to do a foreach loop to retrieve value of each key associated inside the multidimensional associative array iterating through each element but can still get it to work.

Array
(
    [tracks] => Array
        (
            [0] => Array
                (
                    [album] => Array
                        (
                            [album_type] => album
                            [artists] => Array
                                (
                                    [0] => Array
                                        (
                                            [external_urls] => Array
                                                (
                                                    [spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
                                                )

                                            [href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
                                            [id] => 4ovtyvs7j1jSmwhkBGHqSr
                                            [name] => Olamide
                                            [type] => artist
                                            [uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
                                        )

                                )

                            [external_urls] => Array
                                (
                                    [spotify] => https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh
                                )

                            [href] => https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh
                            [id] => 6fG2eFCgUmytQWL6umtsCh
                            [images] => Array
                                (
                                    [0] => Array
                                        (
                                            [height] => 640
                                            [url] => https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77
                                            [width] => 640
                                        )

                                    [1] => Array
                                        (
                                            [height] => 300
                                            [url] => https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77
                                            [width] => 300
                                        )

                                    [2] => Array
                                        (
                                            [height] => 64
                                            [url] => https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77
                                            [width] => 64
                                        )

                                )

                            [name] => Carpe Diem
                            [release_date] => 2020-10-07
                            [release_date_precision] => day
                            [total_tracks] => 12
                            [type] => album
                            [uri] => spotify:album:6fG2eFCgUmytQWL6umtsCh
                        )

                    [artists] => Array
                        (
                            [0] => Array
                                (
                                    [external_urls] => Array
                                        (
                                            [spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
                                        )

                                    [href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
                                    [id] => 4ovtyvs7j1jSmwhkBGHqSr
                                    [name] => Olamide
                                    [type] => artist
                                    [uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
                                )

                            [1] => Array
                                (
                                    [external_urls] => Array
                                        (
                                            [spotify] => https://open.spotify.com/artist/5yOvAmpIR7hVxiS6Ls5DPO
                                        )

                                    [href] => https://api.spotify.com/v1/artists/5yOvAmpIR7hVxiS6Ls5DPO
                                    [id] => 5yOvAmpIR7hVxiS6Ls5DPO
                                    [name] => Omah Lay
                                    [type] => artist
                                    [uri] => spotify:artist:5yOvAmpIR7hVxiS6Ls5DPO
                                )

                        )

                    [disc_number] => 1
                    [duration_ms] => 171764
                    [explicit] => 1
                    [external_ids] => Array
                        (
                            [isrc] => USUYG1330802
                        )

                    [external_urls] => Array
                        (
                            [spotify] => https://open.spotify.com/track/5DS9LiyEdw2zY8bM6kjjgM
                        )

                    [href] => https://api.spotify.com/v1/tracks/5DS9LiyEdw2zY8bM6kjjgM
                    [id] => 5DS9LiyEdw2zY8bM6kjjgM
                    [is_local] => 
                    [is_playable] => 1
                    [name] => Infinity (feat. Omah Lay)
                    [popularity] => 73
                    [preview_url] => https://p.scdn.co/mp3-preview/5159fa17676fc96e32db13b7680f7497d5c2f74d?cid=756f211306ad4c9a934d07c5722790b5
                    [track_number] => 3
                    [type] => track
                    [uri] => spotify:track:5DS9LiyEdw2zY8bM6kjjgM
                )

            [1] => Array
                (
                    [album] => Array
                        (
                            [album_type] => album
                            [artists] => Array
                                (
                                    [0] => Array
                                        (
                                            [external_urls] => Array
                                                (
                                                    [spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
                                                )

                                            [href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
                                            [id] => 4ovtyvs7j1jSmwhkBGHqSr
                                            [name] => Olamide
                                            [type] => artist
                                            [uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
                                        )

                                )

                            [external_urls] => Array
                                (
                                    [spotify] => https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh
                                )

                            [href] => https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh
                            [id] => 6fG2eFCgUmytQWL6umtsCh
                            [images] => Array
                                (
                                    [0] => Array
                                        (
                                            [height] => 640
                                            [url] => https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77
                                            [width] => 640
                                        )

                                    [1] => Array
                                        (
                                            [height] => 300
                                            [url] => https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77
                                            [width] => 300
                                        )

                                    [2] => Array
                                        (
                                            [height] => 64
                                            [url] => https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77
                                            [width] => 64
                                        )

                                )

                            [name] => Carpe Diem
                            [release_date] => 2020-10-07
                            [release_date_precision] => day
                            [total_tracks] => 12
                            [type] => album
                            [uri] => spotify:album:6fG2eFCgUmytQWL6umtsCh
                        )

                    [artists] => Array
                        (
                            [0] => Array
                                (
                                    [external_urls] => Array
                                        (
                                            [spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
                                        )

                                    [href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
                                    [id] => 4ovtyvs7j1jSmwhkBGHqSr
                                    [name] => Olamide
                                    [type] => artist
                                    [uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
                                )

                            [1] => Array
                                (
                                    [external_urls] => Array
                                        (
                                            [spotify] => https://open.spotify.com/artist/68R39izwNAztATrXMOqkJS
                                        )

                                    [href] => https://api.spotify.com/v1/artists/68R39izwNAztATrXMOqkJS
                                    [id] => 68R39izwNAztATrXMOqkJS
                                    [name] => Bad Boy Timz
                                    [type] => artist
                                    [uri] => spotify:artist:68R39izwNAztATrXMOqkJS
                                )

                        )

                    [disc_number] => 1
                    [duration_ms] => 194000
                    [explicit] => 1
                    [external_ids] => Array
                        (
                            [isrc] => USUYG1330809
                        )

                    [external_urls] => Array
                        (
                            [spotify] => https://open.spotify.com/track/558ULLj8yY2vT8XGtgY0q9
                        )

                    [href] => https://api.spotify.com/v1/tracks/558ULLj8yY2vT8XGtgY0q9
                    [id] => 558ULLj8yY2vT8XGtgY0q9
                    [is_local] => 
                    [is_playable] => 1
                    [name] => Loading (feat. Bad Boy Timz)
                    [popularity] => 64
                    [preview_url] => https://p.scdn.co/mp3-preview/7848a9f9ea879e6b1c6618508354e2559678aa8c?cid=756f211306ad4c9a934d07c5722790b5
                    [track_number] => 10
                    [type] => track
                    [uri] => spotify:track:558ULLj8yY2vT8XGtgY0q9
                )

CodePudding user response:

I would approach it like this:

$api = array (
    'tracks' => 
    array (
      0 => 
      array (
        'album' => 
        array (
          'album_type' => 'album',
          'artists' => 
          array (
            0 => 
            array (
              'external_urls' => 
              array (
                'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
              ),
              'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
              'id' => '4ovtyvs7j1jSmwhkBGHqSr',
              'name' => 'Olamide',
              'type' => 'artist',
              'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
            ),
          ),
          'external_urls' => 
          array (
            'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
          ),
          'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
          'id' => '6fG2eFCgUmytQWL6umtsCh',
          'images' => 
          array (
            0 => 
            array (
              'height' => '640',
              'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
              'width' => '640',
            ),
            1 => 
            array (
              'height' => '300',
              'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
              'width' => '300',
            ),
            2 => 
            array (
              'height' => '64',
              'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
              'width' => '64',
            ),
          ),
          'name' => 'Carpe Diem',
          'release_date' => '2020-10-07',
          'release_date_precision' => 'day',
          'total_tracks' => '12',
          'type' => 'album',
          'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
        ),
        'artists' => 
        array (
          0 => 
          array (
            'external_urls' => 
            array (
              'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
            ),
            'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
            'id' => '4ovtyvs7j1jSmwhkBGHqSr',
            'name' => 'Olamide',
            'type' => 'artist',
            'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
          ),
          1 => 
          array (
            'external_urls' => 
            array (
              'spotify' => 'https://open.spotify.com/artist/5yOvAmpIR7hVxiS6Ls5DPO',
            ),
            'href' => 'https://api.spotify.com/v1/artists/5yOvAmpIR7hVxiS6Ls5DPO',
            'id' => '5yOvAmpIR7hVxiS6Ls5DPO',
            'name' => 'Omah Lay',
            'type' => 'artist',
            'uri' => 'spotify:artist:5yOvAmpIR7hVxiS6Ls5DPO',
          ),
        ),
        'disc_number' => '1',
        'duration_ms' => '171764',
        'explicit' => '1',
        'external_ids' => 
        array (
          'isrc' => 'USUYG1330802',
        ),
        'external_urls' => 
        array (
          'spotify' => 'https://open.spotify.com/track/5DS9LiyEdw2zY8bM6kjjgM',
        ),
        'href' => 'https://api.spotify.com/v1/tracks/5DS9LiyEdw2zY8bM6kjjgM',
        'id' => '5DS9LiyEdw2zY8bM6kjjgM
                      [is_local] => ',
        'is_playable' => '1',
        'name' => 'Infinity (feat. Omah Lay)',
        'popularity' => '73',
        'preview_url' => 'https://p.scdn.co/mp3-preview/5159fa17676fc96e32db13b7680f7497d5c2f74d?cid=756f211306ad4c9a934d07c5722790b5',
        'track_number' => '3',
        'type' => 'track',
        'uri' => 'spotify:track:5DS9LiyEdw2zY8bM6kjjgM',
      ),
      1 => 
      array (
        'album' => 
        array (
          'album_type' => 'album',
          'artists' => 
          array (
            0 => 
            array (
              'external_urls' => 
              array (
                'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
              ),
              'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
              'id' => '4ovtyvs7j1jSmwhkBGHqSr',
              'name' => 'Olamide',
              'type' => 'artist',
              'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
            ),
          ),
          'external_urls' => 
          array (
            'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
          ),
          'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
          'id' => '6fG2eFCgUmytQWL6umtsCh',
          'images' => 
          array (
            0 => 
            array (
              'height' => '640',
              'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
              'width' => '640',
            ),
            1 => 
            array (
              'height' => '300',
              'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
              'width' => '300',
            ),
            2 => 
            array (
              'height' => '64',
              'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
              'width' => '64',
            ),
          ),
          'name' => 'Carpe Diem',
          'release_date' => '2020-10-07',
          'release_date_precision' => 'day',
          'total_tracks' => '12',
          'type' => 'album',
          'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
        ),
        'artists' => 
        array (
          0 => 
          array (
            'external_urls' => 
            array (
              'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
            ),
            'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
            'id' => '4ovtyvs7j1jSmwhkBGHqSr',
            'name' => 'Olamide',
            'type' => 'artist',
            'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
          ),
          1 => 
          array (
            'external_urls' => 
            array (
              'spotify' => 'https://open.spotify.com/artist/68R39izwNAztATrXMOqkJS',
            ),
            'href' => 'https://api.spotify.com/v1/artists/68R39izwNAztATrXMOqkJS',
            'id' => '68R39izwNAztATrXMOqkJS',
            'name' => 'Bad Boy Timz',
            'type' => 'artist',
            'uri' => 'spotify:artist:68R39izwNAztATrXMOqkJS',
          ),
        ),
        'disc_number' => '1',
        'duration_ms' => '194000',
        'explicit' => '1',
        'external_ids' => 
        array (
          'isrc' => 'USUYG1330809',
        ),
        'external_urls' => 
        array (
          'spotify' => 'https://open.spotify.com/track/558ULLj8yY2vT8XGtgY0q9',
        ),
        'href' => 'https://api.spotify.com/v1/tracks/558ULLj8yY2vT8XGtgY0q9',
        'id' => '558ULLj8yY2vT8XGtgY0q9
                      [is_local] => ',
        'is_playable' => '1',
        'name' => 'Loading (feat. Bad Boy Timz)',
        'popularity' => '64',
        'preview_url' => 'https://p.scdn.co/mp3-preview/7848a9f9ea879e6b1c6618508354e2559678aa8c?cid=756f211306ad4c9a934d07c5722790b5',
        'track_number' => '10',
        'type' => 'track',
        'uri' => 'spotify:track:558ULLj8yY2vT8XGtgY0q9',
      ),
    ),
);

$tracks = [];

foreach ($api['tracks'] as $track) {
    $_track = [
        'artists' => '',
        'name' => '',
        'album' => '',
        'image' => ''
    ];

    $artists = [];
    foreach ($track['artists'] as $artist) {
        $artists[] = $artist['name'];
    }
    $_track['artists'] = implode(', ', $artists);

    $_track['name'] = $track['name'];
    $_track['album'] = $track['album']['name'];
    $_track['image'] = $track['album']['images'][2]['url'];
    
    $tracks[] = $_track;
}

var_dump($tracks);

Results in:

array(2) {
  [0]=>
  array(4) {
    ["artists"]=>
    string(17) "Olamide, Omah Lay"
    ["name"]=>
    string(25) "Infinity (feat. Omah Lay)"
    ["album"]=>
    string(10) "Carpe Diem"
    ["image"]=>
    string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
  }
  [1]=>
  array(4) {
    ["artists"]=>
    string(21) "Olamide, Bad Boy Timz"
    ["name"]=>
    string(28) "Loading (feat. Bad Boy Timz)"
    ["album"]=>
    string(10) "Carpe Diem"
    ["image"]=>
    string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
  }
}

CodePudding user response:

This is conveniently accomplished with array_walk_recursive. It doesn't matter at what depth or position your url key/value is, it will be found and iterated. As follows:

$urls = []; // For collecting URLs, passed in by reference:

array_walk_recursive($data, function($val, $key) use (&$urls) {
    if($key === 'url') { // if $key is "url", add to $urls; ignore the rest.
        $urls[] = $val;
    }
});

Note that if you have multiple url keys at different depths/positions, they will all be added in. If you need to target a specific depth/position where multiple identical keys may exist, the solution would be a bit more complicated. In your use case this is not an issue, so I've kept it simple.

Also note that array_walk_recursive callback function is only called on the "leaves" or the final values of an array. As such, it will not be called on members that are arrays containing arrays. Non-final array members will simply be followed onward until "leaves" are found.

  • Related