从文本文件读取二维数组,帮助!
更新:我意识到问题是我使用 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”并将其存储在二维数组 $array 中。由于某种原因它返回:
Array[0]
Array[1]
Array[2]
....etc etc
有人知道我做错了什么吗?
UPDATE: I realized that the issue was I was using print instead of echo to print the data, so it was showing the array instead of the data within it. Thanks a ton guys!
I currently have a text file that looks like this:
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
And I'm using this function:
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;
}
Essentially, it's supposed to read through the file, explode each "0" and store it in a 2D array, $array. For some reason it returns this:
Array[0]
Array[1]
Array[2]
....etc etc
Anyone know what I did wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
PHP 多维数组只是数组的数组。不需要内循环。您只需这样做即可
获得相同的效果。
PHP multi-dimensional arrays are just arrays of arrays. There's no need for the inner loop. You can just do
and get the same effect.
您将通过使用 for 循环和计数器来以困难的方式解决这个问题。通过使用 PHP 的
$array[] = $val
附加语法,您可以在这里节省大量精力。或者更简洁:
You're going about it the hard way, by using for loops and counters. By using PHP's
$array[] = $val
append syntax, you can save a lot of effort here.Or to be even more concise:
试试这个:
try this :
嗯,由于这是逗号分隔的,我们可以使用 fgetcsv 来使这个简短而简单:
结果数组:
Hmm, since this is comma delimitated, we can use fgetcsv to make this short and simple:
Resulting array: