在PHP的echo语句中嵌套div元素

10

i have this:

<?php  
       if ( ($cart->count_product) > 0) { 
           print $cart->count_product; 
       } else { 
           print ''; 
       }  
?>

我需要将print $cart->count_product放在<div class="my_class"></div>中。

我尝试了不同的方法,但是语法上缺少了一些东西。如果有人能帮忙,我会很高兴。


2
展示一下你尝试过的内容。 - John Conde
<?php if ( ($cart->count_product) > 0) { print '<div class="my_class">'.$cart->count_product.'</div>'; } else { print ''; } ?> - mrakodol
@LifeIsShort 请看我的回答。这里的else语句没有作用。 - BenM
6个回答

15

您可以执行以下操作:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

如果你想让它包含在你的语句中,请这样做:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

由于上面的内容为真时,您只需要输出它,因此不需要else语句。


2

试一下这个:

<?php  if ( ($cart->count_product) > 0) { ?>
         <div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else { 
          print ''; 
}  ?>

谢谢,但我需要在if语句内部的类。 - Grufas
@LifeIsShort 编辑了答案。请查看。 - Edwin Alex
为什么要一直退出 PHP 然后重新进入呢?此外,这里的 else 语句没有任何实际意义... - BenM
@BenM 哎呀,没注意到。现在已经改正了。感谢您的建议。 - Edwin Alex
我觉得你误解了。我的意思是,为什么要停止PHP执行来输出简单的HTML内容呢?使用echo直接输出要干净得多,而不是在三行中使用三个开头的PHP标签... - BenM

0

把它包起来就行了。

<?php        
    if ( ($cart->count_product) > 0) 
    { 
        echo "<div class='my_class'>";
        print $cart->count_product; 
        echo "</div>";
    }

?>

这里根本没有必要使用else语句。 - BenM
@BenM 你说得对。我只是从原始代码中复制了它。 - ATaylor

0
你可以这样做:
<div class"my_class">
<?php if ($cart->count_product > 0) {
          print $cart->count_product; 
      } else { 
          print ''; 
      } 
?>
</div>

在进入 div 标签之前,我们不处于 PHP 标签中


0

你也可以这样做,

<?php 
if ( ($cart->count_product) > 0) { 
  $print .= "<div class='my_class'>"
  $print .= $cart->count_product; 
  $print .= "</div>"
} else { 
   $print = ''; 
} 
echo  $print;
?>

0

您可以使用以下示例,同时您不需要else子句来打印空值!

 <?php if ( ($cart->count_product) > 0) { ?>
           <div class="my_class">
               <?php print $cart->count_product; ?> 
           </div>
 <?php } ?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接