PHP foreach在foreach问题

cj3*_*333 1 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 />';
}
?>
Run Code Online (Sandbox Code Playgroud)

我打印结果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
Run Code Online (Sandbox Code Playgroud)

Cha*_*les 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;
}
Run Code Online (Sandbox Code Playgroud)

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

此外,请摆脱@错误消除操作员,error_reporting一直向上,并确保你已经打开display_errors.你可能有其他错误,潜伏着你故意忽略,这会导致恐怖故事.