我希望循环只输出一次。相反,它输出两次。这是代码:
$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循环,但我需要针对用户输入检查该数组。
以下是$ postcode的初始化:
$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 :(得分:1)
mysql_fetch_array
为每个返回的结果返回一个关联数组和索引数组。 foreach
循环将循环遍历两次并输出两次。尝试使用mysql_fetch_assoc()
http://php.net/manual/en/function.mysql-fetch-array.php
更好的是,尝试转到mysqli
课程。它更快,mysql
被删除。
答案 1 :(得分: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'];
}
}
}