从文本文件中读取2D数组,HELP



UPDATE:我意识到问题是我使用print而不是echo来打印数据,所以它显示的是数组而不是数组中的数据。谢谢大家!

我目前有一个文本文件,看起来像这样:

0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0
0,0,0,0,0

我正在使用这个功能:

function rFile($fileName){
$resultF = fopen($fileName, "r") or die("can't open file");
$array = array(); //Create the first dimension of a 2D array
$i=0;
while(!feof($resultF)){
  $line = fgets($resultF);
  $line = trim($line, "n");
  $tokens = explode(",",$line);
  $array[$i]=array(); //Create the second dimension of the 2D array
  $tokenCount = sizeof($tokens);
  for($j=0; $j<$tokenCount; $j++){
    $array[$i][$j] = $tokens[$j];
  }
  $i++;
 }
return $array;
  }

本质上,它应该读取整个文件,分解每个"0"并将其存储在2D数组$array中。出于某种原因,它返回这个:

Array[0]
Array[1]
Array[2]
....etc etc

有人知道我做错了什么吗?

PHP多维数组只是数组的数组。不需要内环。你可以直接做

while(...) {
   ... fgets stuff
   $array[$i] = explode(',', $line);
   $i++;
}

并得到相同的效果。

通过使用for循环和计数器,您将艰难地完成这项工作。通过使用PHP的$array[] = $val append语法,您可以在这里节省很多工作。

// all the file handling code...
while(!feof($resultF)){
  $line = fgets($resultF);
  $line = trim($line, "n");
  $tokens = explode(",",$line);
  // Append the line array.
  $array[] = $tokens; //Create the second dimension of the 2D array
}
return $array;

或者更简洁地说:

$array[] = explode(",",$line);

试试这个:

function rFile($filename) {
    $lines = file($filename);
    if ($lines !== false) {
        foreach ($lines as & $line) {
            $line = explode(',', trim($line, 'nr'));           
        }
    }
    return $lines;
}
$f = file($fileName);
$results = array();
foreach ($f as $line) {
    $line = preg_replace("n", "", $line);
    $results[] = explode(",", $line);
}

嗯,由于这是逗号分隔的,我们可以使用fgetcsv使其简短明了:

$file = fopen('test.txt', 'r');
$matrix = array();
while($entries = fgetcsv($file)) {
  $matrix[] = $entries;
}
fclose($file);

结果数组:

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
        )
    [1] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
        )
    [2] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
        )
    [3] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
        )
    [4] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
        )
)

相关内容

  • 没有找到相关文章