如何检索用逗号分隔的数据并将其存储在选中的复选框中。我正在使用explode()
,以便将字符串数据转换为数组。
我的问题是我无法理解这段代码的逻辑。例如,数据是“父母,祖父母,朋友”,我想选中该复选框取决于该数据。先感谢您。这是我的代码不起作用:
<?php
$db_living_whom = explode(",", $fetch['living_whom']);
?>
<label>Living with whom</span></label>
<div class="row">
<?php
foreach ($db_living_whom as $value) {
?>
<div class="col-md-2">
<label class="checkbox-inline">Parents
<input type="checkbox" <?php if($value == "Parent") echo "checked"; ?> disabled>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">Brothers & Sisters
<input type="checkbox" <?php if($value == "Brothers & Sister") echo "checked"; ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Grandparents
<input type="checkbox" <?php if($value == "Grandparents") echo "checked"; ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Other Relatives
<input type="checkbox" <?php if($value == "Other Relatives") echo "checked"; ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Friends
<input type="checkbox" <?php if($value == "Friends") echo "checked"; ?> disabled>
</label>
</div>
<?php } ?>
</div>
在该代码中,复选框加载了4次(由于foreach循环),并且未选中“父母,祖父母,朋友”。
答案 0 :(得分:2)
您不需要foreach循环。它在重复您的复选框。
我更改为preg_split来解决所有空白,然后产生爆炸效果。
然后我使用in_array搜索$ db_living_whom是否包含所涉及的复选框条件,然后相应地将其标记为选中。
我使它像这样工作:
<?php
$fetch = ["living_whom" => "Parents, Grandparents, Friends"];
$db_living_whom = preg_split("/[\s*,\s*]*,+[\s*,\s*]*/", $fetch["living_whom"]);
?>
<label>Living with whom</span></label>
<div class="row">
<div class="col-md-2">
<label class="checkbox-inline">Parents
<input type="checkbox" <?= (in_array("Parents", $db_living_whom)) ? "checked" : "" ?> disabled>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">Brothers & Sisters
<input type="checkbox" <?= (in_array("Brothers & Sister", $db_living_whom)) ? "checked" : "" ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Grandparents
<input type="checkbox" <?= (in_array("Grandparents", $db_living_whom)) ? "checked" : "" ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Other Relatives
<input type="checkbox" <?= (in_array("Other Relatives", $db_living_whom)) ? "checked" : "" ?> disabled>
</label>
</div>
<div class="col-md-2">
<label class="checkbox-inline">Friends
<input type="checkbox" <?= (in_array("Friends", $db_living_whom)) ? "checked" : "" ?> disabled>
</label>
</div>
</div>