2015-06-29 113 views
1

我只想循環輸出一次。相反,它輸出兩次。下面是代碼:而foreach循環輸出兩次

$results = mysql_query($query); 
    while ($c = mysql_fetch_array($results)){ 
     $individualPostcode = explode(",", $c['postcode']); 
     foreach($individualPostcode as $val){ 
      $val = trim($val); //Get rid of spaces 
      if($val === $postcode){ 
       echo $c['url']."<br>"; 
      } 
     } 
    } 
} 

這裏是輸出:

http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield 
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield 
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield 
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield 

我試着取出foreach循環,但我需要去通過陣列檢查對用戶輸入。

這裏是$郵編的初始化:

$userInput = $_POST["input"]; 
if(strlen($userInput) < 4) 
    echo "User Input : ".$userInput."<br>"; 
else //Below gets the first three chars of the users string 
    echo "User Input : $userInput<br>What is being used : ".mb_substr($userInput, 0, 3)."<br>"; 

$postcode = mb_substr($userInput, 0, 3);  
+0

'mysql_ *'語法是**邪惡**! –

+0

'$ postcode'的值是什麼?如果2個記錄的郵政編碼具有相同的逗號分隔列表。它將重演第二張唱片和第一張唱片! –

+0

http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – AgeDeO

回答

1

您可以隨時創建網址的陣列來從如果URL已投入數組檢查複製阻止他們:

$results = mysql_query($query); 
$urlsArr = array(); 
while ($c = mysql_fetch_array($results)){ 
    $individualPostcode = explode(",", $c['postcode']); 
    foreach($individualPostcode as $val){ 
     $val = trim($val); //Get rid of spaces 
     if($val === $postcode){ 
      if (!in_array($c['url'], $urlsArr)) echo $c['url']."<br>"; 
      $urlsArr[] = $c['url']; 
     } 
    } 
} 
+0

我已經添加了這個,它完美的作品。謝謝。 – MrHappySandwich

+0

沒問題:)很高興幫助 –