2012-02-15 93 views
1

我现在有两个数组看起来像这样的:根据数组值检查复选框?

色板:

Array 
(
    [0] => Array 
     (
      [swatch_id] => 8 
      [swatch_file] => orange_swatch.jpg 
     ) 

    [1] => Array 
     (
      [swatch_id] => 9 
      [swatch_file] => pink_swatch.jpg 
     ) 

    [2] => Array 
     (
      [swatch_id] => 10 
      [swatch_file] => green_swtach.jpg 
     ) 

) 

选择的色板:

Array 
(
    [0] => Array 
     (
      [swatches_has_products_id] => 18 
      [swatches_swatch_id] => 8 
      [products_product_id] => 19 
     ) 

    [1] => Array 
     (
      [swatches_has_products_id] => 19 
      [swatches_swatch_id] => 10 
      [products_product_id] => 19 
     ) 

) 

我想检查一个复选框,如果$swatch['swatch_id']等于$selected_swatches['swatches_swatch_id']。我用下面的代码这样做:

<?php foreach ($swatches as $k => $swatch): ?> 
    <li> 
     <img src="<?php echo base_url(); ?>media/images/swatches/<?php echo $swatch['swatch_file']; ?>" height=""/> 
     <input type="checkbox" name="product_has_swatch[]" value="<?php echo $swatch['swatch_id']; ?>" <?php if($swatch['swatch_id'] == $selected_swatches[$k]['swatches_swatch_id']) : ?> checked="checked" <?php endif; ?> /> 
    </li> 
<?php endforeach; ?> 

不过,我得到以下错误,如果没有匹配:

A PHP Error was encountered 
    Severity: Notice 
    Message: Undefined offset: 2 
    Filename: products/create.php 
Line Number: 137 

137线是if检查我是否有匹配;我哪里错了?

回答

0

一种解决方案是:

// make a new array of selected ids 
$newArr = array(); 
foreach($selected_swatches as $val) { 
    array_push($newArr, $val['swatches_swatch_id']); 
} 

// then check with in_array, like: 
<?php foreach ($swatches as $k => $swatch): ?> 
    <li> 
     <img src="<?php echo base_url(); ?>media/images/swatches/<?php echo $swatch['swatch_file']; ?>" height=""/> 
     <input type="checkbox" name="product_has_swatch[]" value="<?php echo $swatch['swatch_id']; ?>" <?php if(in_array($swatch['swatch_id'], $newArr)) : ?> checked="checked" <?php endif; ?> /> 
    </li> 
<?php endforeach; > 

希望它可以帮助

0

因为您没有索引2在选定的色板 array ..这就是为什么它给你的注意。

0
**Check this out it works fine** 

$swatches   = array(0 =>array('swatch_id'=>8,'swatch_file'=>'orange_swatch.jpg'), 
          1 => array('swatch_id'=>9,'swatch_file'=>'ping_swatch.jpg'), 
          2 =>array('swatch_id'=>10,'swatch_file'=>'green_swatch.jpg') 
          ); 
$selected_swatches = array(0 =>array('swatches_has_products_id'=>18,'swatches_swatch_id'=>8,'products_product_id'=>19), 
          1 =>array('swatches_has_products_id'=>19,'swatches_swatch_id'=>10,'products_product_id'=>19), 

          );    

foreach($swatches as $k=>$swatch) : 

    ?> 

<li> 

<input type="checkbox" name="product_has_swatch" value="<?php echo $swatch['swatch_id'];?>" 

<?php 
     if($swatch['swatch_id'] == $selected_swatches[$k]['swatches_swatch_id']): 
       echo "checked = 'checked'"; 
     endif; 
    ?> 


/> 
</li> 
<?php endforeach; ?>