【问题标题】:How to add a PHP if statement within an echo?如何在回声中添加 PHP if 语句?
【发布时间】:2014-07-08 20:16:31
【问题描述】:

我想在 echo 中放置一个 if 语句,但我不太确定该怎么做。这是回声:

if(!$hideProduct) {         
echo '
    <div class="gearBorder">
        <img title="Sold Out" alt="Sold Out" class="soldOut" src="soldout.png" />':"").'
        <div class="gearInfo">
            <h4>' . $productName . '</h4>
            <p class="gearDesc">'. $productDescription .'</p>
            <p class="cost">$' . $productPrice . '</div>
        </div>  
    </div>
';}

在第 3 行,我想将图像包装在 if 语句中:

if($productStatus = '0') {

}

在该语句中包装图像的最佳方式是什么?谢谢!

【问题讨论】:

    标签: if-statement echo


    【解决方案1】:

    您实际上可以在打开它们的同一 PHP 块之外结束控制流块,例如 if 语句。例如,这应该可以:

    <?php if (!$hideProduct) { ?>
        <div class="gearBorder">
    
            <?php if ($productStatus == '0') { ?>
                <img title="Sold Out" ... />
            <?php } ?>
    
            ...HTML...
    
        </div>
    <?php } ?>
    

    如果您不喜欢花括号,也可以分别用冒号 (:) 和 endif 替换它们。请参阅this link 了解更多信息。

    【讨论】:

    • 完美,谢谢你的例子和资源!
    【解决方案2】:

    使用一个数组来保存每个 $productStatus 的 CSS 类(带有背景图像)
    快速高效。当您从 HTML 模式切换到 PHP 模式时,性能会很热。此方法消除了英特尔微代码中的 if elseif 性能损失。

    <style type="text/css">
    .soldout{width:40px;height:40px;background-image: url('soldout.png');}
    .backorder{width:40px;height:40px;background-image: url('backorder.png');}
    .instock{width:40px;height:40px;background-image: url('instock.png');}
    </style>
    
    $icon = array(' class="soldout" ',' class="backorder" ',' class="instock" ');.
    
    echo '<div class="gearBorder"><div ' . $icon[$productStatus] . '></div><div class="gearInfo"> ... ';
    

    我还会使用 4 位彩色 GIF 图标并将其转换为 Base64 MIME
    确保使用 gZip 提供页面,并且 Base64 几乎不会受到惩罚。
    如果您想坚持使用图像文件,请确保使用较大的缓存 max-age 值提供图像。

    background-image: url('data:image/gif;base64,R0lGODlhKAAoAK...');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2018-02-19
      • 2018-11-01
      • 1970-01-01
      • 2013-05-11
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多