PHP Foreach 循环仅显示最后一个结果


PHP Foreach loop only displaying last result

我在处理一些代码时遇到了一些问题,在数组中,我有一个 2 的列表,而该函数只显示列表中的最后一个。

这是代码:

<?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);
    }

?>

为什么这不能正常工作?

除非这是一个精心设计的示例,否则问题是数组中有重复的键:

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

此数组具有单个条目

你可以像这样重构:

$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']);
}