The following two errors appear when there aren't any results:

  • Illegal string offset 'artist' in
  • Invalid argument supplied for foreach()

The code below matches results from what the user has searched and returns information back via the last.fm API, the code doing that is in a different file and isn't causing the issues.

The issues occurs when there are no search results and the foreach loop is attempting to with no data. What is needed is some sort of error catching and nothing I have tried has worked.

With it being a foreach loop a try, catch statement didn't seem to work.

if(!isset($json['results']['artistmatches']['artist'][0]))
    {  
    echo '<div class="alert  alert-danger">Artists Not Found</div>';
    }
    else 
    { 
        foreach ($json['results']['artistmatches']['artist'] as $track) 
        {
            $artist = $track['name'];
            $image = $track['image'][3]['#text'];
            $url =  preg_replace("/ /s","_" , $artist); 
            if($artist&&$image)
            {
                include('./artist_short.php');      
            }
        }

    }
有帮助吗?

解决方案

Add an if statement that checks if the result is an array.

if(is_array($json['results']['artistmatches'])) {

    foreach ($json['results']['artistmatches']['artist'] as $track) 
    {
        $artist = $track['name'];
        $image = $track['image'][3]['#text'];
        $url =  preg_replace("/ /s","_" , $artist); 

        if($artist&&$image)
        {
            include('./artist_short.php');      
        }
    }
} else {
 //handle case where the condition doesn't match.
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top