从文本文件读取2D阵列,请帮助!

问题描述

| 更新:我意识到问题是我正在使用print而不是echo来打印数据,因此它显示的是数组而不是其中的数据。谢谢你们! 我目前有一个文本文件,如下所示:
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
有人知道我做错了吗?     

解决方法

您将通过使用for循环和计数器来艰难地解决问题。通过使用PHP的
$array[] = $val
附加语法,您可以在此处节省很多工作。
// 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);
    ,PHP多维数组只是数组的数组。不需要内部循环。你可以做
while(...) {
   ... fgets stuff
   $array[$i] = explode(\',\',$line);
   $i++;
}
并获得相同的效果。     ,尝试这个 :
function rFile($filename) {
    $lines = file($filename);

    if ($lines !== false) {
        foreach ($lines as & $line) {
            $line = explode(\',trim($line,\'\\n\\r\'));           
        }
    }

    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
        )

)
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...