循环遍历两个数组,而不将结果乘以第一个数组长度*第二个数组长度


Loop through two arrays without multiplying the result by 1st array length * 2nd array length

我有两个数组从服务器响应:

  1. 所有存在的过敏列表
  2. 特定产品过敏清单

我需要显示所有过敏症的复选框列表,并将存在于另一个数组中的复选框标记为选中。

第二个数组可以是null

如何循环遍历两个数组而不将结果乘以array1 * array2

这段代码产生8个复选框输入,因为所有过敏症的列表是4,而产品只有2个过敏症,所以循环执行了8次!

<?php
$checked ="";
if (isset($allergies)) {  // array of all allergies
    foreach ($allergies as $key => $value) {
        if(isset ($productAllergies)) {  // array of product allergies
            foreach ($productAllergies as $productkey => $prodValue) {
                // echo 'product allergy'. $prodValue['allergy_id'] .' general'.$key ;
                if( $prodValue['allergy_id'] ==$key )
                    $checked ='checked';
                else
                    $checked ='';
?>
<?php
            } // foeach close
        } // if close ?>
            <input type="checkbox" name="allergy[]" value="<?php echo $key; ?>"  <?php echo $checked; ?>/> 
            <label>
                <?php echo $value; ?>
            </label>
<?php } // foreach close
} // if close
?>  

谁能帮我澄清一下我应该遵循的逻辑,以显示复选框列表与已选中的值

如果我正确理解了格式,这是可以工作的:

<?php
  $checked ="";     
  if (isset($allergies)) {  // array of all allergies
      foreach ($allergies as $key => $value) {
          if(isset ($productAllergies)){  // array of product allergies
              $k2 = array_search($key, $productAllergies);
              if (!empty($productAllergies[$k2])) {
                 $checked = 'checked';
              }
           }
       }
   }
  ?>