Php 从交叉引用表处理foreach循环中的复选框检查

Php 从交叉引用表处理foreach循环中的复选框检查,php,mysql,checkbox,foreach,Php,Mysql,Checkbox,Foreach,我有三个MySQL表,其中一个是交叉引用表: ----------------------------------- Table name: resources id resource ----------------------------------- Table name: companies id company ----------------------------------- Table name: res_co_xref res_id co_id ---------

我有三个MySQL表,其中一个是交叉引用表:

-----------------------------------

Table name: resources
id
resource

-----------------------------------

Table name: companies
id
company

-----------------------------------

Table name: res_co_xref
res_id
co_id

-----------------------------------
我可以通过以下查询成功加入他们:

SELECT * FROM res_co_xref LEFT JOIN companies ON (companies.id = res_co_xref.co_id) WHERE res_co_xref.res_id=1
结果是:

res_id      co_id
1               12
1               13
1               16
共有10家公司,只有3家公司需要检查此特定资源

这是我的问题代码,当前包含一个嵌套循环。。。结果是每行有三个复选框

<?php foreach ($companyrow as $rowco):?> // this is coming from a PHP class
      <tr>
        <td><?php echo $rowco->company ?></td>
        <td>

        <?php foreach ($rescorow as $rescorowloop):?> // this is from another PHP class

        <div class="sel">
            <label class="checkbox">
              <?php if($rowco->id == $rescorowloop->co_id): ?> // here I successfully checkmark the correct company but there are three checkboxes
              <input type="checkbox" name="company_id[]" value="<?php echo $rowco->id; ?>" checked="checked" />
              <?php  else: ?>
              <input type="checkbox" name="company_id[]" value="<?php echo $rowco->id; ?>" />
              <?php endif; ?>
            </label>
          </div>

          <?php endforeach;?>
          <?php unset($rescorowloop);?>

          </td>
      </tr>
      <?php endforeach;?>
      <?php unset($rowco);?>
//这来自一个PHP类
//这是来自另一个PHP类
//在这里,我成功地勾选了正确的公司,但有三个复选框
通常我会:

 foreach ($thing as $key => $value)
 {

  if ($value == "something that needs to be checked")
  { 
     $chk = "checked='checked'";
  }
  else
  {
     $chk = "";
  }
  echo "<input type='checkbox' name='name' id='id' " . $chk . ">";
}
foreach($thing as$key=>$value)
{
如果($value==“需要检查的内容”)
{ 
$chk=“checked='checked'”;
}
其他的
{
$chk=“”;
}
回声“;
}

这就是您想要的?

我尝试实现您的代码,但无法使其与我的外部参照表一起使用。。。我最终也遇到了同样的问题,例如,一个嵌套循环,每行显示三个复选框。实际上,您的代码确实有帮助!我必须重新定位foreach语句,然后在$chk=“checked='checked'”之后添加一个“break;”;然后我将“echo”放在foreach语句之外。。。。非常感谢你让我走上了正确的道路!