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 code, apologies for the fact it's probably full of errors, misconceptions, rubbish etc.

// 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(
    'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
);

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

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

// convert object to array
$fff = objectToArray($search);

// php-ref to view info about the $fff array
r($fff);

// try to access the total value
$v1 = $fff[0]['artists']['total'];

This is what the php-ref looks like for the $fff variable:

enter image description here

I tried to access the total attribute via:

$v1 = $fff[0]['artists']['total'];

But receive these errors:

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

Sorry for asking a silly question and for not understanding what I'm doing, but, what am I doing wrong?

4532066
  • 2,042
  • 5
  • 21
  • 48
  • What does `$fff` look like??? – AbraCadaver Dec 15 '20 at 21:01
  • Sorry, the image is showing now, I edited the question. – 4532066 Dec 15 '20 at 21:03
  • 1
    Where did you get the `0`? It's just `$fff['artists']['total']`. If you wanted to access `items` then the first would be `$fff['artists']['items'][0]`. – AbraCadaver Dec 15 '20 at 21:05
  • Thank you. I got the `0` from being a knucklehead :-/ out of intest - do you know how I could loop through the `items` records please? I realise I would have to use a loop, but I am not sure how I would traverse that loop inside the `fff` array? Thank you again – 4532066 Dec 15 '20 at 21:09
  • Just `foreach($fff['artists']['items'] as $item) { echo $item['name']; //etc... }`. If one of those like `href` is an array then loop that also or `implode` them or something. – AbraCadaver Dec 15 '20 at 21:11
  • Thank you again for your help – 4532066 Dec 15 '20 at 21:13

0 Answers0