【问题标题】:How to make a switch in PHP? [duplicate]如何在 PHP 中进行切换? [复制]
【发布时间】:2020-03-05 23:51:39
【问题描述】:

我正在尝试在 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”字样。

【问题讨论】:

  • 描述可以包含包含或完全相等???
  • 据我所知看起来还不错。我会仔细检查描述。
  • 你说得对,JSON 响应有更多描述!没有意识到这一点。现在开关工作得很好。
  • stackoverflow.com/a/57164177/2943403 D不要R重复Y我们自己。只写一次echo file_get_content('"./assets/icons/' . $svgs[$description] . '.svg');。请改进您的不清楚的问题。

标签: php switch-statement


【解决方案1】:

我不知道 $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");
}

【讨论】:

  • @mickmackusa 完全同意这个重构!!!
猜你喜欢
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多