我有一个文本文件,里面的数据是:
john,male,20,200,174
joe,male,24,157,166
bea,female,18,153,160
edd,male,30,180,180
我正在使用Laravel,因此在storage / app / upload中有包含此文本文件的文件夹。 在我的控制器中,这是我的代码:
public function readfile()
{
$file = Storage::get('upload/test.txt');
$array = explode(',', $file);
print_r($array);
}
输出为:
Array
(
[0] => john
[1] => male
[2] => 20
[3] => 200
[4] => 174
joe
[5] => male
[6] => 24
[7] => 157
[8] => 166
bea
[9] => female
[10] => 18
[11] => 153
[12] => 160
edd
[13] => male
[14] => 30
[15] => 180
[16] => 180
)
这是我需要发生的事情:
Array
(
[0] => john,male,20,200,174
[1] => joe,male,24,157,166
[2] => bea,female,18,153,160
[3] => edd,male,30,180,180
)
对此我还是陌生的,希望有人能帮助我。预先感谢
答案 0 :(得分:2)
尝试一下
public function readfile()
{
$file = Storage::get('upload/test.txt');
$array = explode(PHP_EOL, $file);
print_r($array);
}
答案 1 :(得分:1)
要获取数组数组(以逗号分隔),请尝试
public function readfile()
$file = Storage::get('upload/test.txt');
$lines = explode("\n", $file);
$array = array_map(function($line) {
return explode(',', $line);
}, $lines);
print_r($array);
}
如果只想获取行数组,则它位于$lines
中。工作示例here
答案 2 :(得分:1)
请尝试以下代码
public function readfile()
{
$file = Storage::get('upload/test.txt');
$fileData = [];
while (!$file->eof()) {
$fileData[] = $file->fgetcsv(",");
}
print_r($fileData);
}