【发布时间】:2021-08-29 12:30:22
【问题描述】:
我有两个数组,下面是输出。第一个数组是我的所有列表,第二个是由用户选择的。
$specification=getgeneralSpecifications($pdo); // getting below array
Array(
[0] => Array
(
[sp_id] => 1
[specifications_name] => example 1
)
[1] => Array
(
[sp_id] => 2
[specifications_name] => example 2
)
[2] => Array
(
[sp_id] => 3
[specifications_name] => example 3
)
[3] => Array
(
[sp_id] => 4
[specifications_name] => example 4
)
[4] => Array
(
[sp_id] => 5
[specifications_name] => example 5
)
[5] => Array
(
[sp_id] => 6
[specifications_name] => example 6
)
)
$getgeneral = explode(",",$info['developerprofile']['general_Specifications']); // getting below output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
我必须显示数据库中的所有列表,并且我已经根据获取表单数据库的第二个数组值选中了复选框。
我尝试了以下代码,我得到了输出但缺少一个值。
我的意思是,如果我有数组 1,2,3,4,那么我将继续使用 1,2,3
<?php
$specification=getgeneralSpecifications($pdo);
$getgeneral = explode(",",$info['developerprofile']['general_Specifications']);
foreach ($specification as $key=> $row) {
$checked="";
if(in_array($key, $getgeneral)){
$checked="checked";
}
?>
<li><label><?php echo $row['specifications_name'];?></label>
<div class="form-check">
<input class="form-check-input custom-checkbox generalsinglecheck" type="checkbox" value="<?php echo $row['sp_id'];?>" name="general_specification[]" <?php echo $checked;?>>
</div>
</li>
<?php } ?>
【问题讨论】:
-
in_array()是你的朋友。见the manual。 -
@Michel,那么我需要使用 foreach 吗?
-
就
if ( in_array ( $row['sp_id'], $your_user_array ) ) -
@mickmackusa,实际上我必须显示所有列表,选择的 .getgeneralSpecifications() 显示所有列表,$getgeneral 显示选择的。
-
@mickmackusa,是的,你是对的,在我尝试相同之前,但现在一些场景更改为现在我必须在用户可以更新更多列表的编辑页面上显示所有列表。跨度>
标签: php html checkbox foreach nested-for-loop