2014-04-07 126 views
0

我遇到了一些代码有点麻烦的地方,我有一个列表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); 

    } 



?> 

这是为什么不能正常工作?

+2

您是否试过在迭代时打印'$ x'的值?我的猜测是,它是你的嵌套循环。 – h2ooooooo

+0

这是什么意思表达:'$ list = array('php.com'=>'php','php.com'=>'php');'?两个键是相同的,所以你最终只有一个单一的元素。当然,基于该数组的foreach循环只会给出单个迭代... – arkascha

回答

2

除非这是一个严重的人为的例子,那么次的问题是你有你的数组中的重复键:

$list = array('php.com'=>'php', 'php.com'=>'php'); 

这个数组的一个条目

你coud重构像这样:

$list = array(

    array('url'=>'php.net', 'keyword'=>'php'), 
    array('url'=>'php.net', 'keyword'=>'arrays'), 
    array('url'=>'php.net', 'keyword'=>'anotherkeyword') 
    ); 


foreach($list as $entry){ 

    getKeywordPosition($entry['url'], $entry['keyword']); 

} 
+0

如果我这样做:$ list = array('php.com'=>'php','php.com'=>'php code “); ...它只会显示最后一个...关键字在这里是不同的,如果我这样做:$ list = array('php.net'=>'php','php.com'=>'php code' );这是完全不同的,我仍然只得到最后的结果,所以它必须是别的 – Satch3000

+0

你确定吗?所以如果你删除foreach循环并添加两个函数调用:getKeywordPosition('php.net','php'); getKeywordPosition('php.com','php code');那么你只能得到一个或两个结果? – Steve

+0

Downvoter关心评论为什么? – Steve