php - 将txt文件读入二维数组

标签 php arrays file

该文件包含 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/

相关文章:

php - 为什么登录时mysql查询不匹配?

javascript - 如何将(二进制)整数转换为数组?

java - 为什么 java.util.concurrent.PriorityBlockingQueue 使用数组而不是链表

java - 如何将 URL 的其余部分与最后一个路径分开

php - 使用php读取wsdl文件

php - PHP 的 Vim 折叠

javascript - 当变量为空时,JavaScript中的三元运算符

Javascript:从数组中删除特定项目并返回没有这些项目的原始数组

python - 按行读取的文件平均排序 Python 3

java - 处理Java : Prevent selectInput from opening indefinitely