0

I am using jwilsson's spotify-web-api-php to return data from the Spotify API using PHP.

Also I'm using digitalnature's php-ref to return info about variables.

This is my (terrible) code:

// https://stackoverflow.com/questions/4345554/convert-a-php-object-to-an-associative-array
function objectToArray($r)
{
  if (is_object($r)) {
    if (method_exists($r, 'toArray')) {
      return $r->toArray(); // returns result directly
    } else {
      $r = get_object_vars($r);
    }
  }

  if (is_array($r)) {
    $r = array_map(__FUNCTION__, $r); // recursive function call
  }

  return $r;
}

$session = new SpotifyWebAPI\Session(
    'aaaaaaaaaaaaaaa',
    'bbbbbbbbbbbbbbb'
);

$session->requestCredentialsToken();
$accessToken = $session->getAccessToken();

$str = $_POST['str'];
$str_length = strlen($_POST['str']);

$html = null;

$api = new SpotifyWebAPI\SpotifyWebAPI();
$api->setAccessToken($accessToken);

$search = $api->search('fugazi','artist');

$search_array = objectToArray($search);

r($search_array);

// loop through the results
foreach($search_array['artists']['items'] as $item) {

    // artist name
    $artist_name = $item['name'];
    $html .= "<h2>$artist_name</h2>";
    
    // genres
    foreach($item['genres'] as $genre) {
        $html .= " <span class='code'>$genre</span> ";
    }
                                        
    // $v2 = $item['images']['0']['height'];
    // r($v2);
    
}

This is what the php-ref shows the $search_array to look like:

enter image description here

Or as plain text: https://0bin.net/paste/iPYfn2M6#Pt8l-a9i9el0TVnZsDTA8wlbe/t0CGSIsp4bds0IZyT

I would like to access the attributes for the first element in the images array for each artist returned.

I tried via this line:

$v2 = $item['images']['0']['height'];

But the following error was returned:

PHP Notice:  Undefined offset: 0 in C:\Websites\spotify\search.php on line 68
PHP Notice:  Trying to access array offset on value of type null in C:\Websites\spotify\search.php on line 68

I have searched around that error but I can't get my head around the correct syntax to use in this example.

Sorry for my lack of understanding.

4532066
  • 2,042
  • 5
  • 21
  • 48
  • could you include a `var_export($search_array);` - pictures are hard to read and it's easier to reproduce with the data. – berend Dec 15 '20 at 21:57
  • Thanks for your reply. I have edited the question to include a link to the pasted var_export version of the array (https://0bin.net/paste/iPYfn2M6#Pt8l-a9i9el0TVnZsDTA8wlbe/t0CGSIsp4bds0IZyT). Thanks – 4532066 Dec 15 '20 at 22:02
  • `echo $arr['artists']['items'][0]['images'][0]['height']; // output: 737` where `$arr` is the source array you var_export() ed. – jibsteroos Dec 15 '20 at 22:10
  • Thank you @jibsteroos - that sorted it :-) – 4532066 Dec 15 '20 at 22:22
  • glad I could help! – jibsteroos Dec 15 '20 at 22:30

0 Answers0