php 嵌套 for 语句?
我正在尝试在 for 循环中处理 for 循环,并且对语法有点警惕......这行得通吗?本质上,我想在计数等于或小于 $count 时为每 1,000 条记录运行代码...下面的语法是否有效,或者是否有更好的方法?
for($x = 0; $x <= 700000; $x++) {
for($i = 0; $i <= 1000; $i++) {
//run the code
}
}
I'm trying to process a for loop within a for loop, and just a little wary of the syntax... Will this work? Essentially, I want to run code for every 1,000 records while the count is equal to or less than the $count... Will the syntax below work, or is there a better way?
for($x = 0; $x <= 700000; $x++) {
for($i = 0; $i <= 1000; $i++) {
//run the code
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您拥有的语法将起作用,但我认为它不会完全满足您的要求。现在,它将执行外循环 700,001 次,而对于这 700,001 次中的每一次,它将执行内循环。
这意味着内部循环总共将运行 700,001 x 1001 = 大约 700.7 百万次。
如果这不是您想要的,您能提供更多信息吗?我无法真正弄清楚“当计数等于或小于 $count 时,我想为每 1,000 条记录运行代码”是什么意思。我根本没有看到任何名为
$count
的变量。The syntax you have will work, but I don't think it's going to do exactly what you want. Right now, it's going to do the outer loop 700,001 times, and for every single one of those 700,001 times, it's going to do the inner loop.
That means, in total, the inner loop is going to run 700,001 x 1001 = about 700.7 million times.
If this isn't what you want, can you give a bit more information? I can't really work out what "I want to run code for every 1,000 records while the count is equal to or less than the $count" means. I don't see any variable named
$count
at all.$f 应该是 fopen() 返回的文件句柄,而不是文件名。
通读 php.net 上的 fopen()、fgets() 文档。如果您需要拆分字符串,您可能还需要explode()。
如果您的文件不大,您可能希望立即将其读入数组,如下所示:
$f should be file-handle returned by fopen(), not a filename.
Read through the documentation at php.net for fopen(), fgets(). You might also need explode() if you need to split your string.
If your file isn't big, you might want to read it into an array at once like this:
要逐行读取文本文件,我通常:
To read a text file line by line I usually:
严格回答这个问题,您会想要更像这样的东西:
但是,您确实应该考虑将文件导入数据库的其他方法之一。
Strictly answering the question, you'd want something more like this:
However, you should really consider one of the other methods for importing files to a database.