我有以下代码:
<p><? echo $langdata['oneprodpage_brand']; ?>:</strong> <? echo $thisproduct['brandname']; ?></p>
显示如下:
品牌名称:{品牌名称}
如果没有给出brand,默认添加"Without brand"(所有数据在DB中排序)
我想做这样的事情,如果php发现这个值"without brand",然后做点什么…
我怎样才能做到呢?
I tried this
<? if ($thisproduct['brandname'] == Without brand) { ?>
<? } else { ?>
<p><? echo $langdata['oneprodpage_brand']; ?>:</strong> <? echo $thisproduct['brandname']; ?></p>
<? }; ?>
但是行不通
你忘记了一些引号没有brand,你的代码将是:
<? if ($thisproduct['brandname'] == "Without brand") { ?>
<? } else { ?>
<p><? echo $langdata['oneprodpage_brand']; ?>:</strong> <? echo $thisproduct['brandname']; ?></p>
<? }; ?>
你想在没有品牌时执行的代码应该在后面:
<? if ($thisproduct['brandname'] == "Without brand") { ?>
:
<? } else { ?>
但是我觉得你的方式真的不太好读,我更喜欢:
<?php
if ($thisproduct['brandname'] == "Without brand") {
// Do something
} else {
echo "<p>". $langdata['oneprodpage_brand'] ."</strong>". $thisproduct['brandname'] ."</p>";
}
?>
你可以尝试这样做:
$withoutBrandNames = array('Without brand');
if (in_array($thisproduct['brandname'], $withoutBrandNames)) {
$thisproduct['brandname'] = 'This product has no brand';
}
echo $thisproduct['brandname'];
或者,如果你像注释建议的那样认为:
if (stristr($thisproduct['brandname'], 'Without brand') === false) {
$thisproduct['brandname'] = 'This product has no brand';
}
echo $thisproduct['brandname'];
我使用了大小写不敏感的比较函数,以防出现大小写异常的可能性,选择当然是你自己的。
PS:正如注释所建议的,如果标签都包含代码,你不必一直打开和关闭标签,你甚至可以使用像这样的短期语法:
<?php if (statement): ?>
<p> Some lovely HTML</p>
<?php else: ?>
<p>Some different lovely HTML</p>
<?php endif; ?>
我讨厌视图文件中的花括号,事实上,我讨厌视图文件中的PHP -但这似乎是必要的