我目前有一个文本文件,如下所示:
0000001
0000002
0000003
0000004
0000005
0000006....
我使用下面的代码将1d数组转换为2d ..
$filename = "surface.txt";
$fp = fopen($filename, "r");
while(!feof($fp)) {
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
for ($i=0; $i<=$row; $i++){
for ($j =0; $j<=$col; $j++){
//echo $lines[$i*$col + $j];
$matrix[$i][$j] = $lines[$i*$col + $j];
//var_dump($matrix[i][j]);
}
}
}
fclose($fp);
我的输出数组$ matrix打印所有NULL值。我已将var_dump()放在循环中以查看它显示的内容。有趣的是,它正在读取所有值,但是,在最后一个值之后,它继续读取为空这也是值,最后使$ matrix为空(NULL)。 我不知道如何解决这个问题。如果我不清楚如何解释输出,请在下面查看..
Array ( [0] => Array ( [0] => 0000001 ) )
Array ( [0] => Array ( [0] => 0000002 [1] => 0000002 ) )
Array ( [0] => Array ( [0] => 0000001 [1] => 0000002 [2] => 0000003 ) )
在最后几行中,我看到输出如下所示
Array ( [0] => Array ( [0] => [1] => [2] => [3] => ) [1] => Array ( [0] => [1] => [2] => [3] => ) [2] => Array ( [0] => [1] => [2] => [3] => ) [3] => Array ( [0] => [1] => [2] => [3] => ) [4] => Array ( [0] => [1] => [2] => [3] => ) [5] => Array ( [0] => [1] => [2] => [3] => ) [6] => Array ( [0] => [1] => [2] => [3] => ) )
非常感谢任何帮助。
答案 0 :(得分:0)
<?php
//asuming $row and $col are defined
//$row=5;
//$col=5;
$filename = "surface.txt";
$content = file_get_contents($filename);
$lines=explode("\n",$content);
foreach ($lines as $rowNum=>$r)
{
$r=str_split($r);
if ($rowNum+1>$row)
break;
if ($r===[""])
continue;
while (count($r)>$col)
{
array_pop($r);
}
$matrix[]=$r;
}
var_dump($matrix);
答案 1 :(得分:0)
以下是我如何使用它
$filename="surface.txt"
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
for ($i=0; $i<$row; $i++){
for ($j =0; $j<$col; $j++){
$matrix[$i][$j] = $lines[$i*$col + $j];
}
}