gpt4 book ai didi

php - 列出用户检查的类别以及 php 中的所有类别

转载 作者:行者123 更新时间:2023-11-30 22:18:33 25 4
gpt4 key购买 nike

我正在处理一个用户表单,其中包含一些类别,它在我的表单中填充为复选框

<td><input type="checkbox" name="category[]" value="1"> CCTV &nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><input type="checkbox" name="category[]" value="2"> Access Control &nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><input type="checkbox" name="category[]"value="3"> Fire Alarm &nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><input type="checkbox" name="category[]" value="4"> Intrusion Alarm System &nbsp;&nbsp;&nbsp;&nbsp;</td>

我会像这样将类别作为逗号分隔的字符串存储在数据库中

$category=implode(',',$_POST['category']);

这应该显示在 view my category 页面中,在这个页面中我想显示用户选择的类别的所有类别(即 如果用户是 CCTV 类别被选中它应该显示为标记),但我不知道如何实现这个目标??

这是我的代码,它显示了没有用户检查值的所有类别

<?php
//fetch user checked category from db and convert to array.
$user_cat=explode(',',$value['category']); //eg;array(5,6,8)
//all categorys value
$all_cat_value=array('1','2','3','4','5','6','7','8');
$all_cat_txt=array('CCTV','Acess controle'....,'Fire alaram');

//populates all category with checked value
for each($all_cat_txt as $key=>$val){
echo '<input type="checkbox" value="'.$[$all_cat_value][$key].'">'.$val;
}

注意:$all_cat_value$all_cat_txt的长度相同

最佳答案

使用in_array() 并检查检查的值是否存在于数组中。如果找到,则在复选框中添加 checked 属性。

//fetch user checked category from db and convert to array.
$user_cat=explode(',',$value['category']); //eg;array(5,6,8)
//all categorys value
$all_cat_value=array('1','2','3','4','5','6','7','8');
$all_cat_txt=array('CCTV','Acess controle',....,'Fire alaram');

//populates all category with checked value
foreach($all_cat_txt as $key=>$val){
$checked = "";
if(in_array($all_cat_value[$key], $user_cat))
{
$checked = "checked";
}
echo '<input type="checkbox" value="'.$all_cat_value[$key].'" '.$checked.'>'.$val;
}

关于php - 列出用户检查的类别以及 php 中的所有类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com