首页 > 解决方案 > 如果值存在,则在编辑页面中选中复选框

问题描述

我在数据库中有类别,管理员可以检查多个类别,但在编辑中,如果管理员之前添加了类别,我想显示复选框

$rows = $util->get_all_categories();
$crows = $util->get_categories_by_user_id($id);


                if($rows) {
                    //all the categories are in $rows array and the $crows carry shows already added categories
                    foreach ($rows as $row) {
                        
                          //this exper work but checked only one checkbox
                        if( $row['name'] == $crow['name']){
                        echo '<label class="block"><input type="checkbox" name="category" checked value="' . $row['ID'] . '"> ' . $row['name'] . '</label>';
                        echo '<br>';
                        }else{
                        echo '<label class="block"><input type="checkbox" name="category" value="' . $row['ID'] . '"> ' . $row['name'] . '</label>';
                        echo '<br>';
                        }
                        
                    }
                    
                }?>

在下面的照片中,您可以看到它只选中一个复选框,其中有多个 https://i.stack.imgur.com/2kfsr.png

标签: php

解决方案


好的。让我们清楚一点。我不知道 $crow['name'] 来自哪里。因为您没有解析 $crows 数组。它是未定义的。

但至于如何使用必要的信息来做到这一点:

<?php
// lets say $util->get_all_categories(); gives you this
$rows = [['ID'=>1, 'name'=>'r1'],['ID'=>2, 'name'=>'r2'],['ID'=>3,'name'=>'r3']];

// and $util->get_categories_by_user_id($id); gives you this
$crows = ['r2', 'r1'];

if($rows) {
  foreach ($rows as $row) {                     
    if(in_array($row['name'],$crows)){
      echo '<label class="block"><input type="checkbox" name="category" checked value="' . $row['ID'] . '"> ' . $row['name'] . '</label>';
      echo '<br>';
    }else{
      echo '<label class="block"><input type="checkbox" name="category" value="' . $row['ID'] . '"> ' . $row['name'] . '</label>';
      echo '<br>';
    }                        
  }                 
}

?>

您的 get_categories_by_user_id($id) 函数必须为您提供一个数组,该数组包含预期的用户类别作为其名称。在我的示例中 ['r2','r1']。否则,您必须将其解析为您解析 $rows 数组 foreach 的方式($rows as $row)。这会导致输出重复且更加混乱。(双循环)。


Extra => 如果你想用更少的代码做同样的事情:

<?php

$rows = [['ID'=>1, 'name'=>'r1'],['ID'=>2, 'name'=>'r2'],['ID'=>3, 'name'=>'r3']];
$crows = ['r2', 'r1'];

if($rows) {
    foreach ($rows as $row) { ?>
        <label class="block">
        <input type="checkbox" name="category" <?php echo in_array($row['name'],$crows) ? 'checked' : '';?>  value="<?php echo $row['ID'];?>"><?php echo $row['name'];?>
        </label>
    <?php
    }
}

?>

推荐阅读