Satch3000
Satch3000

Reputation: 49384

PHP Foreach loop only displaying last result

I am having a bit of trouble with some code where in an array I have a list of 2 and the function is only displaying the last in the list.

Here is the code:

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

    }



?>

Why is this not working properly?

Upvotes: 0

Views: 271

Answers (1)

Steve
Steve

Reputation: 20469

Unless this is a badly contrived example, then th issue is you have duplicate keys in your array:

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

This array has a single entry

You coud refactor like so:

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

}

Upvotes: 2

Related Questions