php - 如果值存在,则在编辑页面中选中复选框
问题描述
我在数据库中有类别,管理员可以检查多个类别,但在编辑中,如果管理员之前添加了类别,我想显示复选框
$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
解决方案
好的。让我们清楚一点。我不知道 $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
}
}
?>
推荐阅读
- javascript - 如何在发送消息/按下按钮时捕获时间/日期[Vanilla Javascript]
- django-auth-ldap - django_auth_ldap 不能使用 populate_user 信号
- apache-kafka - kafka-configs.sh +关于topic的retention.ms删除后的配置是什么
- python - 如何在pyvis中绘制具有社区结构的图
- css - WordPress评论表单验证
- visual-studio-code - 如何在 Visual Studio Code 中配置 launch.json?--path 变量不起作用
- java - 为什么从 parcelablearray 读取时会出现 ClassNotFoundException?
- javascript - 我们能否以一种可以从后端更改内容的方式对 GIF 进行编程
- c# - 字符串的连接
- testng - 无法使用数据提供者实现一项测试的并行执行