目前我正在從我的資料庫中獲取所有值并在它們旁邊放置一個復選框。默認情況下,所有復選框都未選中,但 id 存在于資料庫中的復選框應標記為選中。為此,我使用了以下代碼:
查看類:
<?php if($facilities) foreach($facilities as $facility): ?>
<?php foreach($checked_facility as $key => $value){ ?>
<fieldset id="availablenetworked">
<input type="checkbox" <?php echo ($value['facilities_id'] == $facility['id'] ? 'checked' : ''); ?>
name="facility[]" id="<?php echo $facility['id'] ?>" value="<?php echo $facility['id'] ?>">
<label for="<?php echo $facility['id'] ?>"><?php echo $facility['title'] ?></label>
</fieldset>
<?php } endforeach; ?>
正確執行此操作會選中我資料庫中的所有值,但會弄亂我的視圖并使其看起來像這樣:

$facilities用于獲取設施的所有記錄并$checked_facility用于檢查特定人員選擇的值。
從 $checked_facility 回傳的回應看起來像這樣,我試圖訪問設施 ID 并在我的串列中用復選標記標記所有這些。

uj5u.com熱心網友回復:
您有 2 個嵌套回圈,這可能會導致重復問題。為什么不先預處理您檢查過的 ID 并將它們存盤在一個陣列中。然后您可以在單個回圈中參考它們。就像是
<?php
$checked = array();
foreach($checked_facility as $key => $value){
$checked[]=$value['facilities_id'];
}?>
然后,您可以遍歷您的串列,只需檢查in_array()
https://www.php.net/manual/en/function.in-array.php
<?php if($facilities) foreach($facilities as $facility): ?>
<fieldset id="availablenetworked">
<input type="checkbox" <?php echo in_array($facility['id'], $checked) ? 'checked' : ''; ?>
name="facility[]" id="<?php echo $facility['id'] ?>" value="<?php echo $facility['id'] ?>">
<label for="<?php echo $facility['id'] ?>"><?php echo $facility['title'] ?></label>
</fieldset>
<?php endforeach; ?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368482.html
