我希望循环只输出一次。相反,它输出两次。这是代码:
$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);
您可以始终创建URL的数组,通过检查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'];
}
}
}
mysql_fetch_array
为每个返回的结果返回一个关联数组和索引数组。foreach
循环将在两者上循环并输出两次。尝试使用mysql_fetch_assoc()
http://php.net/manual/en/function.mysql-fetch-array.php
更好的做法是,尝试转到mysqli
类。它的速度更快,mysql
被去复杂化。
http://php.net/manual/en/intro.mysqli.php