2017-04-06 85 views
1

我有一個關於縮短if else語句的問題。我正在嘗試使用OpenWeatherMap API進行天氣應用。但我不喜歡那些圖標。我想改變的圖標是這樣的:如果其他語句使用php縮短

if($desc == 'clear sky'){ 
    $weather_icon = 'clear_sky.png'; 
}else 
if($desc == 'few clouds'){ 
    $weather_icon = 'few_clouds.png'; 
}else 
if($desc == 'scattered clouds'){ 
    $weather_icon = 'scattered_clouds.png'; 
}else 
if($desc == 'broken clouds'){ 
    $weather_icon = 'broken_clouds.png'; 
}else 
if($desc == ''){ 
    ..... 
} 
...... 

所以我的問題是我該怎麼辦,如果要不然這與縮短或你有什麼主意,用不同的認爲?

+0

[轉](http://php.net/manual/en/control-structures.switch.php)! – Jeff

+0

由於switch語句不會更短,但絕對易於閱讀 –

+0

Switch case是一個想法 – Akintunde007

回答

3

數組是凝聚在一起的宇宙(如果宇宙是用PHP編寫)的膠水。

$map = [ 
    'clear sky' => "clear_sky.png", 
    'few clouds' =>"few_clouds.png", 
    'scattered clouds' => 'scattered_clouds.png' 
    'broken clouds' => 'broken_clouds.png' 
]; 

if (isset($map[$desc])) { 
    $weather_icon = $map[$desc]; 
} 

這允許您將不相關的單詞與圖像名稱以及多個單詞映射到同一圖像。

+0

不錯,乾淨的答案。謝謝,我給你投票。 – Azzo

2

如果天氣模式是可預測的,你可以使用一個襯墊:

$img = str_replace (' ' , '_', $desc) . '.png'; 

但是,如果你有,你不能只是改變dynaically一個列表,你可以這樣做:

$descriptions = [ 
    'clear sky'=>'clear_sky', 
    'few clouds'=>'few_clouds', 
    'scattered clouds'=>'scattered_clouds',  
    'broken clouds'=>'broken_clouds',  
]; 

$defaultImg = 'some_empty'; 

$img = !empty($desc) ? $descriptions[$desc] : $defaultImg; 
$img = $img . 'png'; 
+0

我喜歡這個答案。所以我認爲你檢查了[OpenWeatherMap](https://openweathermap.org/weather-conditions)其他天氣情況。您的答案最適合我的解決方案。謝謝親愛的約洛。 – Azzo

3

由於您的描述符合您所尋找的內容,因此您可以這樣做。

if (
    in_array(
     $desc, 
     array(
      'clear sky', 
      'few clouds', 
      'scattered clouds', 
      'broken clouds' 
     ) 
    ) 
) { 
    $weather_icon = str_replace(' ', '_', $desc) . '.png'; 
} 

另一種選擇是使用地圖,他們並不總是匹配。

$map = [ 
    'clear sky' => 'clear_sky.png', 
    'few clouds' => 'few_clouds.png', 
    'scattered clouds' => 'scattered_clouds.png', 
    'broken clouds' => 'broken_clouds.png', 
    'thunderstorm with light rain' => 'few_clouds.png', 
]; 

// $api['icon'] references the original icon from the api 
$weather_icon = array_key_exists($desc, $map) ? $map[$desc] : $api['icon']; 
+0

感謝您的回答,但如果'$ desc ='有小雨的雷暴''那麼如果我想使用圖標'few_clouds.png',那麼我應該如何處理您的代碼? – Azzo

+0

它不會與我給的東西一起工作,我遵循你給出的所有匹配的例子。 – Augwa

+0

謝謝你,我在這裏學到了不同的想法。 – Azzo

0
<?php 
$desc = "clear sky"; 
$weather_icon = str_replace(" ","_",$desc).".png"; 
echo $weather_icon; 
?> 
0

它看起來像你有一些固定的符號。您可以使用此:

<?php 
$desc = 'clear sky'; 
convertDescriptionToImage($desc); 

function convertDescriptionToImage($description) 
{ 
    $arrayCodes = ["clear sky", "few clouds"]; 
    if (TRUE == in_array($description, $arrayCodes)) 
    { 
     return str_replace(" ", "_", "$description.png"); 
    } 

    die("$description not found"); 
}