3 回答

TA貢獻2016條經(jīng)驗 獲得超9個贊
我認為主要的問題是你應(yīng)該總是exit()在使用header()with location后使用,否則頁面會繼續(xù)執(zhí)行。
如果第一個值是唯一值,因為第一個循環(huán)總是如此,這仍然會導(dǎo)致問題exit;。
您可以解決這個問題(只有header()在值 > 2時才調(diào)用,然后在循環(huán)之后所有的默認值都是唯一的),但另一種方法是使用array_count_values()它計算列表中存在的每個值的數(shù)量,然后用于max()查找最常見的一種,然后針對它進行測試......
$no_id=array('100100','100200','100300','100200','100200','100100');
$n = max(array_count_values($no_id));
if($n >= 2)
{
header('location:../../home');
exit;
} else
{
header('location:../../questionnair');
exit;
}
更新:
另一種稍微快一點的版本是使用原始的第一個循環(huán),但是一旦檢測到該值已經(jīng)設(shè)置,它就可以停止工作,然后返回......
$no_id=array('100100','100200','100300','100200','100200','100100');
$array = array();
foreach ($no_id as $key => $value)
{
if(isset($array[$value]))
{
header('location:../../home');
exit;
} else
{
$array[$value] = 1;
}
}
header('location:../../questionnair');
exit;

TA貢獻1798條經(jīng)驗 獲得超3個贊
如果您只需要檢查數(shù)組是否有重復(fù),您可以使用array_unique新數(shù)組和舊數(shù)組進行比較。如果數(shù)組不相同,則意味著存在重復(fù)項。
用代碼:
$no_id = array('100100','100200','100300','100200','100200','100100');
$new_array = array_unique($no_id);
if (count($no_id) == count($new_array)) {
// 2 arrays have same number of items => they are equal => no duplicates
$redirect = "questionnair.php";
} else {
// 2 arrays have different number of items => they are not equal => duplicates
$redirect = "home.php";
}
header("location: {$redirect}");
注意
您必須重定向到另一個 PHP 頁面(例如 home.php 而不僅僅是 home)。

TA貢獻1796條經(jīng)驗 獲得超4個贊
首先,使用array_unique函數(shù)更簡單,它將刪除所有重復(fù)值。之后您可以進行檢查,如果沒有任何更改,則沒有重復(fù)的項目。
像這樣:
$no_id=array('100100','100200','100300','100200','100200','100100');
$no_id_unique = array_unique($no_id);
if(count($no_id)===count($no_id_unique)){
header('location:../../questionnair');
}else{
header('location:../../home');
}
exit();
您../在路徑中使用的下一件事,這意味著go to parent directory. 我不知道你的環(huán)境,但很可能這是一個壞主意。
根據(jù)文檔,最好指定必須轉(zhuǎn)發(fā)用戶的頁面的完整 url:
header("Location: http://www.example.com/home/");
另外,請注意,您需要阻止腳本的所有其他輸出,尤其是在header()調(diào)用之前。在這里閱讀更多。
- 3 回答
- 0 關(guān)注
- 204 瀏覽
添加回答
舉報