如何使用PHP中的foreach循环在多个复选框中设置所选属性?

时间:2019-01-29 14:03:16

标签: php checkbox foreach

我要显示所有类别,并且要将选定的属性设置为多个复选框。

<div class="col-md-10">
<?php 

$allCategories = $category->getAllCategory();

if ($allCategories) {

$categoryAccess = $category_permitted->getCategoriesByUserId($user_info[0]->id);

foreach ($allCategories as $key => $items) {
    if ($categoryAccess) {
        foreach ($categoryAccess as $key => $value) {
            ?>
            <input type="checkbox" name="cat_access[]" value=" <?php echo $items->id ?> " <?php echo (isset($categoryAccess) && @$categoryAccess[$key]->id == $items->id) ? 'checked' : '' ?>><?php echo $items->title?>
            <?php
        }
    }

    ?>

    <?php
}
}
 ?>
    </div>

在遍历$categoryAccess之后,我选择了两个选项,但是我得到的所有类别都重复两次作为输出,即category1类别1类别2类别2类别3类别3类别4类别4。

我有4个带有复选框的类别,对于输出,应检查其中2个类别。我在<?php echo (isset($categoryAccess) && $categoryAccess->id == $items->id) ? 'selected' : '' ?>中遇到错误,它给出了此错误:试图获取非对象的属性'id',当我执行<?php echo (isset($categoryAccess) && $categoryAccess[0]->id == $items->id) ? 'selected' : '' ?>时,它给出的数据仅为0索引。

var_dump($categoryAccess)

array(2)
{
    [0]=> object(stdClass)#6 (3)
    {
        ["id"]=> string(1) "1"
        ["user_id"]=> string(1) "2"
        ["title"]=> string(25) "category1"
    }
    [1]=> object(stdClass)#20 (3)
    {
        ["id"]=> string(1) "3"
        ["user_id"]=> string(1) "2"
        ["title"]=> string(18) "category2"
    }
}

1 个答案:

答案 0 :(得分:2)

尝试一下:

<?php

$allCategories = $category->getAllCategory();
$categoryAccess = $category_permitted->getCategoriesByUserId($user_info[0]->id);

foreach ($allCategories as $items) {

  $checked = '';    

  foreach ($categoryAccess as $value) {

    if($items->id == $value->id){
      $checked = 'checked';
      break;
    } 
  }
  ?>

  <input type="checkbox" name="cat_access[]" value="<?php echo $items->id ?>" <?php echo $checked ?>>
  <?php echo $items->title?>

  <?php
}
?>