micky micky - 4 months ago 11
HTML Question

Getting the value checked from database

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]);
}


and in the html form is:

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


With the first loop, i get the values of all the categories checked. and with the second loop, i get the values of all the categories also checked from first. what I want is not to get that values of checked categories in the second loop. Hope you understand.

Answer

May be you can store the IDS from first loop into array display only those which are not found in array in second loop.

Just like this,

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

In above code we're saving IDs of category in $arrayofcategories and checking (in second loop) if they are already found in first loop, Display only if they're not found.

Comments