在foreach外面显示checked =“已检查”

时间:2015-05-21 05:24:41

标签: php foreach

如果文章的值匹配,我有需要显示的复选框。但是我现在需要将它应用到复选框html中,但我不能将输入包装在foreach中,因为它不能满足我的需要。

如何将检查的值放在html中而不将其包装在foreach中?

PHP:

<?php 

foreach($searchRows as $searchRow) { 

    if ($article->id==$searchRow->aid) {
        $true = 'checked="checked"';
    } 
} 

?>

HTML:

<input type="checkbox" <?php echo $true;?>/>

上面的代码显示了每个复选框都已选中。我只想检查匹配的值。

干杯 约翰

2 个答案:

答案 0 :(得分:1)

将数据存储在相应的打印中 -

foreach($searchRows as $searchRow) { 
  if($article->id==$searchRow->aid){
    $true[$article->id] = 'checked="checked"';
  } else {
    $true[$article->id] = '';
  } 
} 

在输入中 -

<input type="checkbox" <?php echo $true[$articleId];?>/> // Something like this

如果您要打印文章的复选框。

答案 1 :(得分:0)

您的方法是正确的,但首先您必须将$true的值定义为空白,如果您的if条件匹配,那么每次$true保持'checked="checkexd"'后,您就不会这样做。

使用此代码

<?php 

$true = '';   //Define first blank the variable

foreach($searchRows as $searchRow) { 

if($article->id==$searchRow->aid){

$true = 'checked="checked"';

} } 

?>

<input type="checkbox" <?php echo $true;?>/>