2017-07-15 114 views
0

我有一些將xml內容保存到變量的代碼。其中一個變量可以是1-240的數字。基於範圍(如1-30,30-60,60-90等),我想將一些文本保存到一個新變量中。根據第一個變量的輸出將輸出保存到新變量

我目前的代碼有問題(我對PHP相當陌生,但趕上了)。例如,我從xml文檔($storm_wind)中保存的變量爲100,根據我的代碼,應將$category變量保存爲2。然而,這樣可以節省變量5(這我假設是因爲我的代碼中的最後一行是$category = '5';什麼是執行這個代碼?我應該使用elseif語句,而不是正確的方法是什麼?

下面是一個代碼片段,目前沒有工作:

$wind_value = $xml->channel->item[0]->nhcCyclone->nhcwind; 
$storm_wind = substr($wind_value, 0, -4); 

if(($storm_wind >=1) && ($storm_wind <=38); { 
    $category = 'TD'; } 
if($storm_wind >=39 && $storm_wind <=73); { 
    $category = 'TS'; } 
if($storm_wind >=74 && $storm_wind <=95); { 
    $category = 1; } 
if($storm_wind >=96 && $storm_wind <=110); { 
    $category = 2; } 
if($storm_wind >=111 && $storm_wind <=129); { 
    $category = 3; } 
if($storm_wind >=130 && $storm_wind <=156); { 
    $category = 4; } 
if($storm_wind >=157 && $storm_wind <=240); { 
    $category = 5; } 
+0

https://phpcodechecker.com/不返回語法錯誤 – USTropics

+0

檢查語法,如果使用分號,則不應該終止。 –

+0

@localheinz僅供參考,我回滾了編輯,因爲你實際上編輯了造成問題的錯誤,沒有這些錯誤,答案就沒有意義了。 – jmattheis

回答

2

刪除及早終止您if結構分號,如:

if($storm_wind >=1 && $storm_wind <=38); { 
    $category = 'TD'; } 

應該是:

if($storm_wind >=1 && $storm_wind <=38) { 
    $category = 'TD'; } 

等等。


發生了什麼事在你的代碼是一個if構造可以採取以下形式:

if(expression) statement; 

沒有花括號單個語句 - 這個語句可以是空的。所以

if(expression); 

本身是一個完整的,孤立的構造。你恰好在每個跟隨一個無關的語句塊包裹在大括號中。因此,您的if構造中的每一個都沒有做任何動作,並且依次將$category設置爲每個值,最後將其保留爲5。

1

雖然問題已經由保羅回答說,是的,你可以使用elseif減少執行的語句的數量:

if ($storm_wind >=1 && $storm_wind <=38) { 
    $category = 'TD'; 
} elseif ($storm_wind >=39 && $storm_wind <=73) { 
    $category = 'TS'; 
} elseif ($storm_wind >=74 && $storm_wind <=95) { 
    $category = 1; 
} elseif ($storm_wind >=96 && $storm_wind <=110) { 
    $category = 2; 
} elseif ($storm_wind >=111 && $storm_wind <=129) { 
    $category = 3; 
} elseif ($storm_wind >=130 && $storm_wind <=156) { 
    $category = 4; 
} elseif ($storm_wind >=157 && $storm_wind <=240) { 
    $category = 5; 
} 

或者,你可以提取功能,並返回早期:

function stormCategoryFrom($windSpeed) 
{ 
    if ($windSpeed >= 157) { 
     return 5; 
    } 

    if ($windSpeed >= 130) { 
     return 4; 
    } 

    if ($windSpeed >= 111) { 
     return 3; 
    } 

    if ($windSpeed >= 96) { 
     return 2; 
    } 

    if ($windSpeed >= 74) { 
     return 1; 
    } 

    if ($windSpeed >= 39) { 
     return 'TS'; 
    } 

    return 'TD'; 
} 

或者:

function stormCategoryFrom($windSpeed) 
{ 
    $categories = [ 
     157 => 5, 
     130 => 4, 
     111 => 3, 
     96 => 2, 
     74 => 1, 
     39 => 'TS', 
    ]; 

    foreach ($categories as $minimumSpeed => $category) { 
     if ($windSpeed >= $minimumSpeed) { 
      return $category; 
     } 
    } 

    return 'TD'; 
} 

另外,在看https://en.m.wikipedia.org/wiki/Tropical_cyclone_scales#Comparisons_across_basins它看起來你是一個。