【问题标题】:Read txt file into two-dimensional array将txt文件读入二维数组
【发布时间】:2013-06-13 11:36:28
【问题描述】:

该文件包含 3 列(制表符分隔)和 10 行。如何从数组 $lines 中获取 [column][row]?目前该数组包含 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];
}

【问题讨论】:

  • 你可以使用 explode("\t") 来获取列。
  • 看看使用PHP内置的fgetcsv()函数而不是fgets()
  • @Cobra_Fast outch,需要睡觉 ;) 谢谢!

标签: php arrays file


【解决方案1】:

为了您的特殊目的,以下 sn-p 将起作用:

$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(),它在这种情况下很方便。它返回一个包含文件所有行的数组。

【讨论】:

    猜你喜欢
    • 2014-04-06
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多