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

如何在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
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置