doulaozhang0238 2015-08-25 01:20
浏览 14
已采纳

PHP:如果没有正确选择

I am building a list based off of a CSV file. Here are the two most common lines in the CSV file:

10,11,12,13,14,15,16    
12,13,14,15,16,0,0

The file is read line-by-line and stored into the list. Here is the code:

while(($current_line = fgets($find_products, 4096)) !== false) {
    list($weight1, $weight2, $weight3, $weight4, $weight5, $weight6, $weight7) = explode(",", $current_line);
}

I look at the value of each item in the list, and print if the value is not 0. Here is the code:

if($weight1 != '0') {
    print '<option>'.$weight1.' lb.</option>';
}

if($weight2 != '0') {
    print '<option>'.$weight2.' lb.</option>';
}

if($weight3 != '0') {
    print '<option>'.$weight3.' lb.</option>';
}

if($weight4 != '0') {
    print '<option>'.$weight4.' lb.</option>';
}

if($weight5 != '0') {
    print '<option>'.$weight5.' lb.</option>';
}

if($weight6 != '0') {
    print '<option>'.$weight6.' lb.</option>';
}

if($weight7 != '0') {
    print '<option>'.$weight7.' lb.</option>';
}

Here are the results of the code after it is run on a CSV file with the above two lines:

10 lb.
11 lb.
12 lb.
13 lb.
14 lb.
15 lb.
16 lb.

AND

12 lb.
13 lb.
14 lb.
15 lb.
16 lb.
0 lb.

The 0 lb. should not be showing up based on the value of $weight6 and $weight7. I have printed the values of these two variables, and they appropriately show up as 0. I can also confirm through testing that the if-statement for $weight7 is the culprit, but I have no idea what is causing the issue. Any help would be greatly appreciated!

  • 写回答

1条回答 默认 最新

  • douming4359 2015-08-25 01:39
    关注

    The reason is that fgets() returns the line with a newline at the end. So $weight7 is "0 " (that's why var_dump says the length is 3), not "\0". You should trim the line before you split it, to remove this.

    while(($current_line = fgets($find_products, 4096)) !== false) {
        $current_line = trim($current_line);
        list($weight1, $weight2, $weight3, $weight4, $weight5, $weight6, $weight7) = explode(",", $current_line);
    }
    

    Or you could instead use fgetcsv() rather than fgets(). It automatically trims the line and splits it at the separator, returning an array that you can iterate over.

    while ($weights = fgetcsv($find_products)) {
        foreach ($weights as $w) {
            if ($w != '0') {
                echo "<option>$w lb.</option>";
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路