简体   繁体   English

如何在此循环中跳过空结果或错误?

[英]How do I skip empty result or errors in this loop?

I do have a loop which store data into mysql... 我确实有一个将数据存储到mysql中的循环...

/connect to your database 
//read your text file into an array, one entry per line

$lines = file('name.txt'); 

//loop through each website URL you read from the file 
foreach ($lines as $name) { 

//do some code
//Insert data to MySQL
 mysql_query("INSERT INTO table (data1,data2) VALUES ('$data1','$data2')");

} 

My problem is when the code returns empty..then it gives error and stop...so how can I skip this and continue to next name so loop wont stop until it finished? 我的问题是当代码返回空..然后给出错误并停止...所以我如何跳过此操作并继续使用下一个名称,这样循环就不会停止直到完成?

foreach($lines as $line){
    if(empty(trim($line)){ continue; }
    // do your insert, etc.
}

If all you you want to do is check for an empty line, this will do that. 如果您只想检查一个空行,则可以这样做。

Good luck! 祝好运!

You could try opening the file like so: 您可以尝试像这样打开文件:

file('name.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

which might work, according to the documentation for file on php.net. 根据php.net上文件的文档,这可能有效。

Empty-Check: if(trim($var) == '') 空检查: if(trim($var) == '')

if you want to use if(empty(trim($var))) , please read the manual entry for empty: 如果要使用if(empty(trim($var))) ,请阅读手册中的空白:

empty() only checks variables as anything else will result in a parse error. empty()仅检查变量,否则将导致解析错误。 In other words, the following will not work: empty(trim($name)). 换句话说,以下内容将不起作用:empty(trim($ name))。

Skip the rest of the current loop iteration : If you can check this then you can use continue . 跳过当前循环的其余部分 :如果可以进行检查,则可以使用Continue This skips the actual loop and continues with the next. 这将跳过实际的循环并继续下一个循环。

Reading files : As Phoenix mentioned, the following code gives you an array which represents the file: 读取文件 :如Phoenix所述,以下代码为您提供了一个表示文件的数组:

// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

FILE_IGNORE_NEW_LINES removes \\n, but lets some empty elements in your array. FILE_IGNORE_NEW_LINES删除\\ n,但在数组中保留一些空元素。 FILE_SKIP_EMPTY_LINES and FILE_IGNORE_NEW_LINES together remove empty line. FILE_SKIP_EMPTY_LINES和FILE_IGNORE_NEW_LINES一起删除空行。 empty means only \\n is in this line! 空意味着只有\\ n在这一行! If you have a space character in it, it's not empty! 如果其中有空格字符,则说明它不是空的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM