2017-08-13 153 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