PHP-为if else语句分配一个变量
我还没有找到一个可靠的答案。是否可以为if/else语句分配一个变量,这样我就不必在某些HTML中包含整个语句 例如,这是正确的吗?如果不是,正确的方法是什么PHP-为if else语句分配一个变量,php,Php,我还没有找到一个可靠的答案。是否可以为if/else语句分配一个变量,这样我就不必在某些HTML中包含整个语句 例如,这是正确的吗?如果不是,正确的方法是什么 $agency = if ($event == "Tornado Watch" || $event == "Severe Thunderstorm Watch") { echo "NWS Storm Prediction Center"; } elseif ($event == "Hurrican
$agency = if ($event == "Tornado Watch" || $event == "Severe Thunderstorm Watch") {
echo "NWS Storm Prediction Center";
} elseif ($event == "Hurricane Watch" || $event == "Tropical Storm Watch") {
echo "NWS National Hurricane Center";
} else {
echo $wfo;
}
我认为您要做的是根据某种逻辑为$agency指定一个值,然后响应$agency的值
<?php
$agency = $wfo;
if ($event == "Tornado Watch" || $event == "Severe Thunderstorm Watch")
{
$agency = "NWS Storm Prediction Center";
}
elseif ($event == "Hurricane Watch" || $event == "Tropical Storm Watch")
{
$agency = "NWS National Hurricane Center";
}
echo $agency;
我使用了Rob的解决方案,因为在我看来,它更干净,代码更少。话虽如此,我还是想扔掉这个对我也有效的解决方案。有人提到我也在考虑的切换语句。所以我在看到罗布的答案之前就试过了,这对我很有效。因此,这是一种替代方法,即使罗布的应该是选择的解决方案
$agency = '';
switch($event)
{
case 'Tornado Watch':
$agency = 'NWS Storm Prediction Center';
break;
case 'Severe Thunderstorm Watch':
$agency = 'NWS Storm Prediction Center';
break;
case 'Hurricane Watch':
$agency = 'NWS National Hurricane Center';
break;
case 'Tropical Storm Watch':
$agency = 'NWS National Hurricane Center';
break;
case 'Flash Flood Watch':
$agency = $wfo;
break;
}
不是那样,但你可以使用三元运算符或开关盒。如果
注意到,你所拥有的将会抛出一个意想不到的。你想达到什么目的?首先,我不确定为什么投票被否决,所以请解释一下。第二,我正在努力实现的目标已在我的帖子中说明。我试图避免在div标记中插入整个语句。只需插入一个变量,并将核心逻辑保留在核心php.1中,就更简洁了。我没有投反对票。2.为什么你不能只使用一个函数呢?Rob给出的答案是你需要的,但也要注意,在你的情况下,文本太长了。事件可以替换为一些较小的值。例:1代表龙卷风,2代表雷雨,等等。这样你就不会冒着在字符串中输入错误的风险。啊,很好,这都取决于你如何安排逻辑,这个解决方案完全让我糊涂了。PHP又骗了我。谢谢我想说我更喜欢这种方式——尽管我总是建议在switch语句中使用默认值,以防您错过了一个案例,但您的观点是正确的。在我的例子中,虽然我也使用了array_过滤器,所以我已经知道这是唯一的情况。既然你提到了,我想我可以用我的最后一句话作为默认值。
$agency = '';
switch($event)
{
case 'Tornado Watch':
$agency = 'NWS Storm Prediction Center';
break;
case 'Severe Thunderstorm Watch':
$agency = 'NWS Storm Prediction Center';
break;
case 'Hurricane Watch':
$agency = 'NWS National Hurricane Center';
break;
case 'Tropical Storm Watch':
$agency = 'NWS National Hurricane Center';
break;
case 'Flash Flood Watch':
$agency = $wfo;
break;
}