我遇到了一些代码有点麻烦的地方,我有一个列表2,函数只显示列表中的最后一个。PHP Foreach循环只显示最后一个结果
下面是代码:
<?php
function getKeywordPosition($theurl,$thekeywords) {
$theurl = $theurl;
$thekeywords = $thekeywords;
$found = false;
$x = 0;
for($x; $x < 64 && $found == false;)
{
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".stripslashes(str_replace(' ', '%20', $thekeywords)).'&start='.$x;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.boo.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
$x4 = $x + 4;
$old_x = $x;
for($x; $x < $x4 && $found == false; $x = $x + 1)
{
if (strpos($json->responseData->results[$x-$old_x]->unescapedUrl, strtolower($theurl)) !== false)
{
$found = true;
}
}
// now have some fun with the results...
}
if($found)
{
echo '<strong>'.$theurl.'</strong> is located as the <strong>'.$x.'</strong> result when searching for <strong>'.stripslashes($thekeywords).'</strong>';
echo '<br>';
}
}
$list = array('php.com'=>'php', 'php.com'=>'php');
foreach($list as $key => $value){
getKeywordPosition($key,$value);
}
?>
这是为什么不能正常工作?
您是否试过在迭代时打印'$ x'的值?我的猜测是,它是你的嵌套循环。 – h2ooooooo
这是什么意思表达:'$ list = array('php.com'=>'php','php.com'=>'php');'?两个键是相同的,所以你最终只有一个单一的元素。当然,基于该数组的foreach循环只会给出单个迭代... – arkascha