PHP - 为if else语句分配变量

时间:2017-08-13 22:50:08

标签: php

我未能找到一个可靠的答案。是否可以将变量分配给if / else语句,因此我不必将整个语句包含在某些HTML中。

例如,这是正确的,如果不是正确的方法吗?

$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;
        }

2 个答案:

答案 0 :(得分:2)

我认为您要做的是根据某些逻辑为$ 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;

[编辑]您可能会发现,将所有字符串比较分解为控制结构并创建关联数组以将事件映射到代理商时,您可能会更难以维护。有很多方法可以做到这一点,这里只是一个简单的方法:

<?php
$eventAgencyMap = [
    'Tornado Watch'             => 'NWS Storm Prediction Center',
    'Severe Thunderstorm Watch' => 'NWS Storm Prediction Center',
    'Hurricane Watch'           => 'NWS National Hurricane Center',
    'Tropical Storm Watch'      => 'NWS National Hurricane Center'
];

$agency = (array_key_exists($event, $eventAgencyMap)) ? $eventAgencyMap[$event] : $wfo;

答案 1 :(得分:1)

我使用Rob的解决方案作为IMO它更干净,代码更少。有了这个说我也想抛出这个对我有用的解决方案。有人提到我正在考虑的开关声明。所以我在看到Rob的答案之前尝试过,这对我很有帮助。所以它是一种替代方式,即使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;

}