该文件包含 3 列(制表符分隔)和 10 行。如何从数组 $lines 中获取[列][行]?目前该数组包含 10 行。
$handle = @fopen('results.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
for($i=0; $i<count($lines); $i++)
{
echo $lines[$i];
}
最佳答案
对于您的特殊目的,以下代码片段将起作用:
$array = array(
array(), array(), array()
);
foreach(file('results.txt') as $line) {
// use trim to remove the end of line sequence
$record = explode("\t", trim($line));
$array [0][]= $record[0];
$array [1][]= $record[1];
$array [2][]= $record[2];
}
请注意,我正在使用函数 file()
在这种情况下这很方便。它返回一个包含文件所有行的数组。
关于php - 将txt文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17086089/