我想檢查我的陣列是否包含重復值。我有一個表格,我使用以下方法傳遞章節 ID:
<input name="chapter_id[]" type="number" value="<?= $row_chapter_list['chapter_id'] ?>">
要更新我的資料庫,我選擇此輸入并在沒有任何問題的情況下進行更新:
if (isset($_POST['chapter_id'])) {
// Update Kapitelnummer
$statement = $pdo->prepare("UPDATE questionaire_chapter SET chapter_id = :chapter_id WHERE id = :id");
$statement->bindParam(":chapter_id", $chapter_id, PDO::PARAM_STR);
$statement->bindParam(":id", $id, PDO::PARAM_INT);
foreach ($_POST['chapter_id'] as $index => $chapter_id) {
$id = $_POST['chapter_inc_id'][$index];
$statement->execute();
}
}
典型的 var_dump 結果如下所示:
陣列(3) { [0]=> 字串(1) "1" [1]=> 字串(2) "12" [2]=> 字串(2) "12" }
在此陣列示例中,值“12”存在于兩個字串中。我想創建一個機制來計算雙精度值并在 PHP if/else 中使用結果。我想避免重復的章節 ID 被寫入我的資料庫。
我第一次嘗試計算字串是這樣的:
print_r(array_count_values($_POST['chapter_id']));
這給了我這樣的結果
Array ( [1] => 1 [12] => 2 )
現在我錯過了實作 if else 來檢查結果是否不是 1 的方法。知道怎么做嗎?
uj5u.com熱心網友回復:
您可以使用array_unique()來獲取已過濾掉任何重復項的陣列。使用它,您可以將其與原始陣列進行比較:
if ($array != array_unique($array)) {
echo "The arrays are not the same, which means that there are duplicates";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407527.html
標籤:
