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

时间:2011-05-25 02:34:53

标签: php multidimensional-array

更新:我意识到问题是我使用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

任何人都知道我做错了什么?

5 个答案:

答案 0 :(得分:2)

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

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

并获得相同的效果。

答案 1 :(得分:1)

通过使用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);

答案 2 :(得分:0)

试试这个:

function rFile($filename) {
    $lines = file($filename);

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

    return $lines;
}

答案 3 :(得分:0)

嗯,因为这是逗号分隔,我们可以使用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
        )

)

答案 4 :(得分:0)

$f = file($fileName);

$results = array();

foreach ($f as $line) {
    $line = preg_replace("\n", "", $line);
    $results[] = explode(",", $line);
}