PHP foreach在foreach问题

时间:2011-03-10 20:16:31

标签: php foreach

我想从第一个和第二个foreach中插入一些值到数据库中,但是我遇到了一些麻烦。我在代码中写了我的问题。我无法解决这两个循环问题。我请求帮助。

<?php
header('Content-type:text/html; charset=utf-8');
set_time_limit(0);
require_once ('../conn.php'); 
require_once ('../simple_html_dom.php');
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&q=obama&key={api-key}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body = curl_exec($ch);
curl_close($ch);
$data = json_decode($body);
foreach ($data->responseData->results as $result) { 
$title = html_entity_decode($result->titleNoFormatting);
$link = html_entity_decode($result->unescapedUrl);
$html = @file_get_html($link );
foreach(@$html->find('h3') as $element) {
     $table=$element;
         echo $table;// here while the $table is empty, echo is null.  
}
echo $table;// here while the $table is empty, echo will repeat the prev $table value.  
mysql_query("SET NAMES utf8");
 mysql_query("INSERT INTO ...");// I want insert all the $title and $table into database.
} 
echo '<hr />';
}
?>

我打印结果while the $table is empty, echo will repeat the prev $table value

Organizing for America | BarackObama.com

Barack Obama - Wikipedia, the free encyclopedia

President Barack Obama | The White House
President Obama Nominates William Francis Kuntz, II to the United States District Court//the prev value

Change.gov - The Official Web Site of the
President Obama Nominates William Francis Kuntz, II to the United States District Court//here the $table is empty, it will repeat the prev $table value, and it should be empty.

Barack Obama on Myspace
Idle Friends▼

ob (obama) on Twitter
Piè di pagina

Barack Obama
Advertise with the NY Daily News!

Barack Obama on the Issues
Voting Record

1 个答案:

答案 0 :(得分:6)

PHP的变量初始化和范围规则很有趣。

初始化 $table。它首先被引用两个foreach深度。 PHP允许这样做,并且不会抱怨它。

问题在于您不断尝试将其设置为某个值,但您从未实际重置

在内部null之前将其初始化为foreach

$html = file_get_html($link );
$table = null;  // <-- New!
foreach($html->find('h3') as $element) {
     $table = $element;
     echo $table;
}

这可确保在foreach完成后,$table将为null,或者它将是您提取的HTML文档中的最后一个H3元素。 (顺便说一句,如果你确实想要最终的H3,你可能只需抓住find返回的数组并查看最后一个元素而不是循环遍历。)

另外,请摆脱@错误消息操作员,将error_reporting完全转向,并确保您已启用display_errors。您可能有其他错误潜伏着故意忽略,这会导致恐怖故事。