【问题标题】:if statement on one line if possif 语句在一行 if poss
【发布时间】:2010-12-31 06:01:15
【问题描述】:

我正在使用生成的 ID 打印图像。但是我想检查一下这个图像是否存在,如果它不打印 no-image.jpg 而是...

<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" /> 

如果可以将其保留在一行上,那就太好了。任何帮助将不胜感激。

【问题讨论】:

    标签: php conditional-operator language-construct


    【解决方案1】:

    哇,这个问题被很多人问和回答:

    http://en.wikipedia.org/wiki/Ternary_operation

    你可以这样做:

    <img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >
    

    【讨论】:

    • 我想他可能一直在问更多关于如何检查图像是否可用的问题。
    • 是的,但这也很有用:)
    • 哦,确实,我有点处于自动模式嘿嘿
    【解决方案2】:

    Kristopher Ives 说了什么,file_exists

    echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")
    

    顺便说一句,您的 sn-p 不太可能工作,因为您似乎将纯 HTML 输出和 PHP 组合在一起,而没有将 PHP 放入 &lt;? ?&gt;

    【讨论】:

      【解决方案3】:

      我的建议实际上是在不输出 html 的单独 php 逻辑块中从 html 标记本身抽象决策...这里有一个缩写示例,假设您没有使用模板引擎,或者MVC 框架。

      <?php
      $filename = 'th.jpg';
      $filePath = '/public/images/' . $row['id'] '/';
      $webPath  = '/images/' . $row['id'] . '/'; 
      //Logic to get the row id etc
      if (!file_exists($filePath . $filename)) {
          $filename ='no-image.jpg';
          $webPath  = '/images/';
      }
      ?>
      <img src="<?php echo $webpath . $filename;?>" />
      

      【讨论】:

      • 我忘了解释为什么 :P 在这种情况下,它将您的业务逻辑与您的表示逻辑分开,允许您稍后对其进行抽象,如果您使用框架或决定重组您的代码,并且从实际显示的逻辑中调出确定使用哪个源路径的逻辑,并尽量减少在你的html中穿插的php代码。
      • 这个很详细,谢谢。我会在未来的版本中这样做,我肯定会看到好处。再次感谢!
      猜你喜欢
      • 2015-05-16
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多