PHP警告:非法字符串偏移&为foreach()提供的参数无效

时间:2014-04-29 18:38:29

标签: php error-handling warnings

如果没有任何结果,则会出现以下两个错误:

  • 中的非法字符串偏移'艺术家'
  • 为foreach()提供的参数无效

下面的代码与用户搜索的结果相匹配,并通过last.fm API返回信息,执行该操作的代码位于不同的文件中,并且不会导致问题。

当没有搜索结果并且foreach循环尝试没有数据时,会出现问题。我需要的是一些错误捕获,我尝试过的任何工作都没有。

由于它是一个foreach循环尝试,catch语句似乎不起作用。

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');      
            }
        }

    }

1 个答案:

答案 0 :(得分:1)

添加if语句,检查结果是否为数组。

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.
}