2017-08-13 156 views
-4

我还没有找到一个可靠的答案。是否有可能为if/else语句分配一个变量,所以我不必在一些HTML中包含整个语句。PHP - 为if语句分配一个变量

例如,这是正确的,如果不是正确的方式是什么?

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

不是这样,但你可以使用三元运算符或开关案例。你在那里会发出一个'意想不到的通知'。 –

+0

你想达到什么目的? – fubar

+0

首先不确定为什么这是投下来的,所以请解释。其次,我想要达到的是在我的文章中提到的。我试图阻止必须在div标签内插入整个语句。只要插入一个变量并将核心逻辑保存在核心php中就更简洁了。 – Texan78

回答

2

我想你想要做的是根据某种逻辑给$代理分配一个值,然后回显$ 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; 
+0

啊,非常好,这就是你如何安排逻辑,解决方案完全滑倒我。 PHP再次愚弄我。谢谢! – Texan78

1

我用Rob的解决方案,国际海事组织它更干净了一点,更少的代码。有了这个说法,我想抛出这个解决方案,也为我工作。有人提到了我正在考虑的switch语句。所以在我看到罗布的回答之前,我尝试了它,这对我很好。所以这是一种替代方式,即使罗布应该是选择的解决方案。

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

} 
+0

我想说我更喜欢这种方式 - 虽然我总是建议在switch语句中默认情况下,以防您错过了一个案例 – Kvothe

+0

您提出了一个很好且有效的观点。在我的情况下,虽然我也使用array_filter,所以我已经知道这些是唯一的情况。现在你提到它,我想我可以使用我的最后一个声明作为默认值。 – Texan78