[英]Splitting txt file delimited by tabs into multidimensional associative array
我目前正在尝试读取如下所示的输入文件:
annie Tuesday October 7 at 08:32 pm 1 Cappuccino 2.5
它由制表符分隔。 我正在尝试从名为orders.txt的文件中读取该文件,并将其放置为关联数组$ array。 这是我到目前为止的代码。 我尝试了几种不同的版本,但没有骰子。
function read_file() {
$file = "orders.txt";
$array = array();
if(file_exists($file)) {
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
foreach($lines as $line) {
$splode = explode("\t", $line);
$array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}
有人可以在这里看到我在做什么错吗? 谢谢。
您的代码看起来不错。 我确实添加了一个if语句,以确保splode在分配之前很久才5。 这是为了防止文件末尾出现空白行。
我在这里的测试文件上运行了几行,并正确处理并按预期输出。
根据创建此文件的方式-每行的末尾可以有一个'\\ r'或'\\ r \\ n'而不是一个\\ n吗? 这是您需要检查的内容-也许是十六进制编辑器,但是我仍然认为您的代码应该可以正常运行(除非只是\\ r),只要有足够的选项卡来满足每行中的5个(我有条件地满足此条件)在我的建议下)。
function read_file()
{
$file = "orders.txt";
$array = array();
if (file_exists($file)) {
echo "Get";
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
var_dump($lines);
foreach ($lines as $line) {
$splode = explode("\t", $line);
if (sizeof($splode) >= 5) $array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.