我正在使用yahoo api - 并且几乎不用他们的例子。但我收到的错误如下:为foreach()提供的参数无效
以下是实际的foreach声明:
foreach ($data->query->results->result as $r){
// do something with the data
}
我正在运行的整个代码在这里:
$c =curl_init("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20state%3D'delaware'%20and%20city%20%3D%20'smyrna'%20and%20query%3D'pizza'&format=json");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 20); // query times out after 20 seconds
$data = curl_exec($c); // I asked for data format to be in json in the query it appears to be returned decoded
//print_r($data);
$data = curl_exec($c);
if ($data === FALSE) {
die("Curl failed with error: " . curl_error($c));
}
$data = json_decode($data);
if (is_null($data)) {
die("json_decode failed with error: " . json_last_error());
}
foreach ($data->query->results->result as $r){
// do something with the data
}
$ data是一个解码的json响应 - 它有数据,看起来我的结构是正确的 - 我只是想循环并显示商业名称 - 例如 - 但是没有去。
答案 0 :(得分:1)
应该是$data->query->results->Result
。请注意,大写结果。
帮助您使用JSON。将整个JSON字符串粘贴到this utility中,然后直观地看到树结构。
答案 1 :(得分:1)
json_decode要求你传递一个额外的布尔参数,如果你想要它返回一个ARRAY而不是一个对象。
$data = json_decode($data,TRUE);
if (is_null($data)) {
die("json_decode failed with error: " . json_last_error());
}
foreach ($data['query']['results]'['Result'] as $r){
// do something with the data
}