2016-07-05 74 views
0
public function actionEditmul($id) 
{ 
     $sql1="SELECT * FROM category_product INNER JOIN category ON category_product.cat_id=category.cat_id WHERE category_product.product_id=$id"; 
     $editcat=Yii::$app->db->createCommand($sql1)->queryAll();    
     $cat=Category::find()->all(); 
     return $this->render('editmul',['category'=>$cat,'editcat'=>$editcat]); 
} 

,并在HTML表单检查值:充分利用数据库

    <?php foreach ($editcat as $edit): ?> 
       <input type="checkbox" name="cat[]" checked="checked" value="<?php echo $edit['cat_id'];?>" ><?php echo $edit['category'];?><br> 
       <?php endforeach; ?> 

       <?php foreach ($category as $categories): ?> 
       <input type="checkbox" name="cat[]" value="<?php echo $categories->cat_id;?>"><?php echo $categories->category;?><br> 
       <?php endforeach; ?> 
       <br>  

随着第一个循环,我得到检查了所有类别的值。在第二个循环中,我得到了所有类别的值,这些值也是首先检查的。我想要的不是在第二个循环中获取检查类别的值。希望你能理解。

+0

的可能的复制[PHP的echo从数据库中检查(http://stackoverflow.com/questions/12674147/php-echo-checked-from-database) –

回答

0

也许您可以将IDS从第一个循环存储到数组显示中,而不是仅在第二个循环中找到数组。

就这样,

<?php $arrayofcategories=array(); ?> 
<?php foreach ($editcat as $edit): ?> 
    <?php $arrayofcategories[]=$edit['cat_id']; ?> 
    <input type="checkbox" name="cat[]" checked="checked" value="<?php echo $edit['cat_id'];?>" ><?php echo $edit['category'];?><br> 
<?php endforeach; ?> 

<?php foreach ($category as $categories): ?> 
    <?php if(!in_array($categories->cat_id,$arrayofcategories)) { ?> 
      <input type="checkbox" name="cat[]" value="<?php echo $categories->cat_id;?>"><?php echo $categories->category;?><br> 
    <?php } ?> 
<?php endforeach; ?> 

在我们保存类别的标识在$arrayofcategories和检查(在第二循环),如果他们在第一循环已经发现上面的代码中,只显示如果他们不找到。

0

你可以试试这个代码:

<?php 
$editCategory = array(); 
foreach ($editcat as $edit): 
$editCategory = $edit['cat_id']; 
?> 
<input type="checkbox" name="cat[]" checked="checked" value="<?php echo $edit['cat_id'];?>" ><?php echo $edit['category'];?><br> 
<?php endforeach; ?> 

<?php foreach ($category as $categories): ?> 
    <?php if (!in_array($categories->cat_id, $editCategory)): ?> 
     <input type="checkbox" name="cat[]" value="<?php echo $categories->cat_id;?>"><?php echo $categories->category;?><br> 
    <?php endif: ?> 
<?php endforeach; ?> 
<br>