I currently have a text file that looks like this:
0000001
0000002
0000003
0000004
0000005
0000006....
I am using the code below to convert 1d array to 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);
My output array $matrix prints all NULL values.I have put var_dump() inside the loop to see what it displays.. Interestingly, It is reading all the values,but, after the last value, it kept on reading empty values too, which inturn made the $matrix empty(NULL) at last. I don't know how to fix this problem. If I am not clear in explaining how the output appears, please look at it below..
Array ( [0] => Array ( [0] => 0000001 ) )
Array ( [0] => Array ( [0] => 0000002 [1] => 0000002 ) )
Array ( [0] => Array ( [0] => 0000001 [1] => 0000002 [2] => 0000003 ) )
In the last lines, I see that the output is like below
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] => ) )
Any help is highly appreciated..
<?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);
Here is how I got it to work
$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];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.