php 循环读取文件的每一行到它自己的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19503878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop read each line of a file to its own array
提问by Vereonix
I have a text file, it can vary in number of lines, but will always have 24 tab deliberated entries on each line.
我有一个文本文件,它的行数可能会有所不同,但每行总是有 24 个经过选项卡审议的条目。
4 of these entries are dates, but they're not in the normal YYYY-MM-DD format example: "2013-03-11T20:35:33+00:00" so I use substr and thats all fine. However currently I pass all the data from the file to a table then take each date do the substr and UPDATE the fields, to then pass all this table to another but with the date field types as "DATE" as first time round they can't due to "2013-03-11T20:35:33+00:00".
其中 4 个条目是日期,但它们不是正常的 YYYY-MM-DD 格式,例如:“2013-03-11T20:35:33+00:00”,所以我使用 substr 就可以了。但是目前我将文件中的所有数据传递到一个表中,然后将每个日期进行 substr 和 UPDATE 字段,然后将所有这些表传递给另一个表,但日期字段类型为“DATE”作为第一轮他们可以'由于“2013-03-11T20:35:33+00:00”。
The point I'm getting at is, I'd like to read each line into an array apply the substr to the dates which will always be in the same position then, pass the array into the table, so the data type for the column can be DATE from the get go.
我要说的一点是,我想将每一行读入一个数组,将 substr 应用于将始终处于相同位置的日期,然后将数组传递到表中,因此列的数据类型从一开始就可以是 DATE。
I just can't seem to figure out how to loop round for each line in the file. I can get the first line (as I need to delete that), I've read that getting a specific line is impossible or hard but I just need it to loop through them periodicity.
我似乎无法弄清楚如何为文件中的每一行循环。我可以得到第一行(因为我需要删除它),我读过获取特定行是不可能或很难的,但我只需要它来循环遍历它们。
I currently have
我目前有
while ($DateRow = mysql_fetch_array($DateQuery, MYSQL_ASSOC))
which loops for each row in the table but I don't know how or if this can be implimented for the file lines.
which 为表中的每一行循环,但我不知道如何或是否可以为文件行实现。
Many thanks.
非常感谢。
回答by Robbie Averill
You're using a database function to loop through a database table - that's fine. To get file contents into an array, use file().Example:
您正在使用数据库函数来遍历数据库表 - 这很好。要将文件内容放入数组,请使用 file()。例子:
$filename = 'info.txt';
$contents = file($filename);
foreach($contents as $line) {
echo $line . "\n";
}
回答by AbraCadaver
All of the substr()
stuff could be made easier with strtotime()
and/or date()
I'm sure:
所有的substr()
东西都可以变得更容易strtotime()
和/或date()
我敢肯定:
$lines = file('/path/to/file.txt');
foreach($lines as $row) {
//whatever here
}