首页 > 解决方案 > php - 多个复选框将检查数据何时加载有效值

问题描述

我正在编写html,php代码。我的html:

<input type="checkbox" name="food[]" value="apple"/>
<input type="checkbox" name="food[]" value="banana"/>
<input type="checkbox" name="food[]" value="something"/>

我确实在数据库中获取并保存了多个复选框的值。当我得到数据库时:

Array([0]=>'apple',[1]=>'banana')

我的问题是,如果数组的值类似于复选框的值,我想检查复选框,但我不能。

标签: php

解决方案


大概您希望能够检查您的复选框,如果它们的值是从数据库返回的(这就是我所理解的):

<?php
function checkit($queryArr, $val)
{
    # If a value is in the array from the database, add checked attribute
    return (in_array($val, $queryArr))? ' checked="checked"' : '';
}
# Array back from database
$queryArr = ['apple','banana'];
?>

<input type="checkbox" name="food[]" value="apple"<?php echo checkit($queryArr, 'apple') ?> />
<input type="checkbox" name="food[]" value="banana"<?php echo checkit($queryArr, 'banana') ?>/>
<input type="checkbox" name="food[]" value="something"<?php echo checkit($queryArr, 'something') ?>/>

推荐阅读