How to get a value inside an array with PP

0

I have an API with some information and I want to get the genre: Samba / Pagode

stdClass Object
(
    [id] => 46484422
    [title] => Raça Negra e Amigos II (Ao Vivo)
    [upc] => 7891430177379
    [link] => https://www.deezer.com/album/46484422
    [share] => https://www.deezer.com/album/46484422?utm_source=deezer&utm_content=album-46484422&utm_term=0_1529271972&utm_medium=web
    [cover] => https://api.deezer.com/album/46484422/image
    [cover_small] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/56x56-000000-80-0-0.jpg
    [cover_medium] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/250x250-000000-80-0-0.jpg
    [cover_big] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/500x500-000000-80-0-0.jpg
    [cover_xl] => https://e-cdns-images.dzcdn.net/images/cover/45f27e183464715a67145b985dcbbd82/1000x1000-000000-80-0-0.jpg
    [genre_id] => 79
    [genres] => stdClass Object
        (
            [data] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 79
                            [name] => Samba/Pagode
                            [picture] => https://api.deezer.com/genre/79/image
                            [type] => genre
                        )

                )

        )

    [label] => Som Livre

My Code:

<?php
  $api = "https://api.deezer.com/album/46484422";
  $url = file_get_contents("$api");
  $json = json_decode($url, true); //This will convert it to an array
  $titulo = $json['title'];
  $capa1000x1000 = $json['cover_xl'];
  $musicas = $json['tracks'];
  $genero = $json['genres'];
?>

<?php echo $genero ?>

However, I wanted to write the name of the Genre, but of this error:

  

Notice: Array to string conversion in \ api.php on line 29 Array

    
asked by anonymous 17.06.2018 / 23:49

1 answer

2

As an array, and there can be more than one genre, do not you want to have a cycle to catch all genres?

If you only want the first one, it would only be $json['genres']['data'][0]['name'] , but if one of these keys, genres , data is not set, it will give error, even if data is empty, because you are always try to access the first one.

EDIT

Cycle example with HTML. In the place in the page where you want to present the genres, you can for something of this kind. It does not have to be a <ol> , it can be any other html element that later you have to use CSS to give styles.

// ... html anterior que está na pagina ...

<ol>
<?php foreach ($json['genres']['data'] as $genero): ?>
    <li><?php echo $genero ?></li>
<?php endforeach; ?>
</ol>

// ... resto do html
    
18.06.2018 / 00:09