douquan1953
2019-01-29 14:03
浏览 227
已采纳

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

I want to display all the category and I want to set selected properties to multiple Checkboxes.

<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>

After looping through $categoryAccess I got two options selected but I am getting all category repeating twice as an output i.e category1 category 1 category 2 category 2 category 3 category 3 category 4 category 4.

I have 4 categories which have checkboxes and for the output, 2 of the categories should be checked. I am getting error in <?php echo (isset($categoryAccess) && $categoryAccess->id == $items->id) ? 'selected' : '' ?> it gives this error: Trying to get property 'id' of non-object and when I do <?php echo (isset($categoryAccess) && $categoryAccess[0]->id == $items->id) ? 'selected' : '' ?> it gives data but of 0 index only.

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条回答 默认 最新

  • drxrgundk062317205 2019-01-29 14:23
    已采纳

    Try this:

    <?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
    }
    ?>
    
    点赞 评论

相关推荐 更多相似问题