如何在PHP中进行切换?

如何在PHP中进行切换?,php,switch-statement,Php,Switch Statement,我试图在PHP中进行切换,但它不起作用。也许我没有理解switch语句的用途,或者我完全错误地使用了它 switch ( $currentWeather->weather[0]->description ) { case 'clear sky': echo file_get_contents("./assets/icons/sunshine.svg"); break; case 'few clouds': echo file_get

我试图在PHP中进行切换,但它不起作用。也许我没有理解switch语句的用途,或者我完全错误地使用了它

    switch ( $currentWeather->weather[0]->description ) {
  case 'clear sky':
      echo file_get_contents("./assets/icons/sunshine.svg");
      break;
  case 'few clouds':
      echo file_get_contents("./assets/icons/sun-cloud.svg"); 
      break;
  case 'scattered clouds':
      echo file_get_contents("./assets/icons/cloud.svg");
      break;
  case 'broken clouds':
      echo file_get_contents("./assets/icons/cloud.svg");
      break;
  case 'shower rain':
      echo file_get_contents("./assets/icons/rain-cloud.svg");
      break;
  case 'rain':
      echo file_get_contents("./assets/icons/rain-cloud.svg"); 
      break;
  case 'thunderstorm':
      echo file_get_contents("./assets/icons/thunder-cloud.svg");
      break;
  case 'snow':
      echo file_get_contents("./assets/icons/snow-cloud.svg");
      break;
  case 'mist':
      echo file_get_contents("./assets/icons/mist-cloud.svg");
      break;
  default:
      echo file_get_contents("./assets/icons/sunshine.svg");
      break;
}

它只显示默认值。我从$currentWeather获得了一个JSON文件,然后描述可以包含任何“case”字。

我不知道当它失败时,
$currentWeather->weather[0]->description
等于什么,但更好的方法(不管怎样,长度更短,您不会重复很多代码)是使用一个查找数组:

$images = ['clear sky' => 'sunshine.svg']; //etc... add the rest of them

if(isset($images[$currentWeather->weather[0]->description])) {
    echo file_get_contents("./assets/icons/" . $images[$currentWeather->weather[0]->description]);
} else {
    echo file_get_contents("./assets/icons/we_dont_know.svg");
}

描述可以包含或完全相等???就我所知看起来还行。我会仔细检查描述。你完全正确JSON响应有更多描述!我不知道。现在开关工作得很好。不要重复你自己。只写一次
echo file\u get_content('.''./assets/icons/'.$svgs[$description]..svg');
!!!