我想插入一些值從第一和第二foreach到數據庫,但我遇到了一些麻煩。我在代碼中寫下我的問題。我無法解決雙迴路問題。我請求幫助。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
這裏沒問題,還是我錯了?只是看到一堆代碼。 – KingCrunch 2011-03-10 20:20:27
那麼,你的問題是什麼?發生了什麼事情,不應該發生什麼或不應該發生什麼? – 2011-03-10 20:29:35
@Rocket,如果我想插入到數據庫中,我將使用第二個'echo $ table;'(在第一個foreach循環中)。但是當我打印結果時,第二位總統奧巴馬提名威廉弗朗西斯昆茲二世去美國地區法院//這裏的美元表應該是空的,但它會重複美元表的價值並回應出來。不正確。 – cj333 2011-03-10 20:34:01