2017-04-06 103 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"); 
}