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 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web