PHP - 如果为null值

4

我有以下的代码:

<div class="product-top-icons">
  <div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
  <div class="energy-rating-2"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_two');?>.jpg"></div>
  <div class="energy-rating-3"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_three');?>.jpg"></div>
  <div class="guarantee-icon"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('warranty');?>.jpg"></div>
</div>

我想在这里添加一个if语句,基本上是要说以下内容:
如果“energy_rating_one”属性中的值为空,则不显示division “energy-rating-1”,如果“energy_rating_two”属性为空,则不显示div“energy-rating-2”,以此类推...

5
这里的 PHP 在哪里? - Dogbert
5个回答

4

类似这样的:

<?php if($_product->getAttributeText('energy_rating_one') !== null): ?>
<div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
<?php endif; ?>

并且对于其他所有内容也是如此。

根据你的喜好,if( ):endif 是一个选择。 (我认为将其与HTML混合使用看起来更好) - Svish
2
要么使用 is_null(),要么使用 !==。仅使用 != 是不够的,因为 0"" 等应该是有效的。 - KingCrunch
@Svish 是的,你说得对。if(): endif 更适合前端。if{} 更适合后端。但有时我会混用它们 :) - Christophe

0
 <?php
   function echoIfExists($argument) {
      $val = $_product->getAttributeText($argument);
      if($val)
           /*your echo stmt*/
   }

echoIfExists('energy_rating_one');
 /** continue here*/

 ?>

0
你在这篇文章中有一个名为"int_to_words"的函数,将"int"值转换为文本值。 http://www.php.net/manual/en/function.strval.php#41988
之后,你只需要迭代遍历所有的值。
for(i = 0; i < 100; i++) {
    $item = 'energy_rating_'.int_to_words($i);
    if($_product->getAttributeText($item) != null){
      echo "<div class=\"energy_rating_$i\"><img src=\"http://www.justhome.co/skin/frontend/default/just2011/images/assets/".$_product->getAttributeText($item).".jpg\"></div>";
    }
}

0

简化一下。只需要将 CSS 类规则从 energy-rating-1 更改为 energy-rating-one,并回显您已经拥有的变量,即 energy-rating-one


-3

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