duanli5662 2017-07-15 01:38
浏览 7
已采纳

根据第一个变量的输出将输出保存到新变量

I have some code that saves xml content to variables. One of those variables can be a number that ranges from 1-240. Based on a range (like 1-30, 30-60, 60-90, etc), I want to save some text to a new variable.

My current code is having issues (I'm fairly new to php, but catch on quick). For instance, my saved variable from the xml document ($storm_wind) was 100, which according to my code, should have saved $category variable as 2. However, it saves the variable as 5 (which I'm assuming is because my last line in the code is $category = '5';. What is the proper way to execute this code? Should I be using elseif statements instead?

Below is a snippet of the code that is currently not working:

$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; }
  • 写回答

2条回答 默认 最新

  • dongyuli4538 2017-07-15 02:08
    关注

    Remove the semicolons that are terminating your if constructs early, e.g.:

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

    Should be:

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

    and so on for all of them.


    What's happening in your code is that an if construct can take the form of:

    if(expression) statement;
    

    without curly braces for a single statement - and the statement can be empty. So

    if(expression);
    

    is itself a complete, isolated construct. You just happen to be following each with an unrelated statement block wrapped in braces. So each of your if constructs are doing nothing, and $category is being set to each value in turn, leaving it at 5 at the end.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办