我有关于if语句的php相关问题。我有这段代码:
<?php if(count($targetValue) > 0 ): ?>
<?php foreach($targetValue as $key=>$val): ?>
<div class="<?php echo $key ?>">
<span>
<?php echo $val ?>
</span>
</div>
<br>
<?php endforeach; ?>
<?php endif;?>
$ val最多可以返回10个预定义的不同值。我需要知道如何检查一个值是否等于一个单词,然后显示它。
示例:如果$ val ==“Pinda”然后显示X.之后,如果$ val ==“Mosterd”则显示Y.
对于$ val返回的每个选项,我想显示不同的图像。
此致
更新:
我现在有了这个代码:
<?php $targetValue = explode(",", $_product->getResource()->getAttribute('nf_allergie')->getFrontend()->getValue($_product)); ?>
<?php if(count($targetValue) > 1 ): ?>
<?php foreach($targetValue as $key=>$val): ?>
<div class="<?php echo $key ?>">
<span>
<?php
switch($val){
CASE "Ei":
echo 'X';
break;
CASE "Gluten":
echo 'X';
break;
CASE "Lupine":
echo 'X';
break;
CASE "Melk, inclusief lactose":
echo 'X';
break;
CASE "Mosterd":
echo 'X';
break;
CASE "Noten":
echo 'X';
break;
CASE "Pinda":
echo 'X';
break;
CASE "Schaaldieren":
echo 'X';
break;
CASE "Selderij":
echo 'X';
break;
CASE "Sesamzaad":
echo 'X';
break;
CASE "Soja":
echo 'X';
break;
CASE "Sulfiet":
echo 'X';
break;
CASE "Vis":
echo 'X';
break;
CASE "Weekdieren":
echo 'X';
break;
default:
echo "Leeg";
}
?>
</span>
</div>
<br>
<?php endforeach; ?>
<?php endif;?>
但是只有第一个将与X一起返回的结果,看起来像foreach不合适?
具有姓名的人:在其前面是检查其是否有效的实际结果
答案 0 :(得分:1)
您可以执行以下操作:
$possibleValues = array(
1 => "Mosterd",
2 => "Pinda",
3 => "Cookie"
);
//add more items to the array as you please
foreach($targetValue as $key => $val ) {
//return the value of the value associated with the key
echo $possibleValues[$key];
}
答案 1 :(得分:0)
您可以使用三元运算符
<?php if(count($targetValue) > 0 ): ?>
<?php foreach($targetValue as $key=>$val): ?>
<div class="<?php echo $key ?>">
<span>
<?php echo (($val== 'pinda') ? 'X' : $val) ;?>
</span>
</div>
<br>
<?php endforeach; ?>
<?php endif;?>
如果您有更多值,可以使用开关
<?php if(count($targetValue) > 0 ): ?>
<?php foreach($targetValue as $key=>$val): ?>
<div class="<?php echo $key ?>">
<span>
switch($val){
CASE 'Pinda':
echo 'X';
break;
CASE 'Mosterd':
echo 'Y';
break;
CASE 'Salad':
echo 'Z';
break;
DEFAULT:
echo $val;
break
}
<?php echo (($val== 'pinda') ? 'X' : $val) ;?>
</span>
</div>
<br>
<?php endforeach; ?>
<?php endif;?>