我希望循环只输出一次。相反,它输出两次。以下是代码:
$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); 发布于 2015-06-29 10:01:15
您可以始终创建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'];
}
}
}发布于 2015-06-29 09:31:37
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
https://stackoverflow.com/questions/31112026
复制相似问题