我有一个文件,我需要将文件的内容保存在我的MySQL数据库中.这是我用来解析文件的代码:
I have a file and I need the save the content of the file in my MySQL database. Here is the code that I am using to parse the file:
$lines = file($tmp_filename); $data = array(); if (($handle = fopen($tmp_filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE) { $key = array_shift($row); $data[$key] = $row; } fclose($handle); }这是我正在解析的文件的内容:
and here are the contents of the file that I am parsing:
HDR;Payroll Interface;5496;2012-07-20 NM1;082;IN2;12345678;2001-01-15;Mr;Marcial;Gustav;Gustav,Marcial;PRI;Marcial PR1;082;IN2;12345678;7 The School;Alvarez;Bahaghari; ;Gandum PR2;082;IN2;12345678;400006;IND;M;M;2007-10-16;1976-03-31 PR3;082;IN2;12345678; ; ;A; **truncated**单击此处以获取完整数据
在某些情况下,数组具有相同的索引和相同的值,但是我仍然需要保存这些数据,但是会发生数组覆盖.必须添加什么才能将同一数组放入不同的数组索引?
There are scenarios where the array has the same index and the same value but I still need to save these data but array overwriting occurs. What must be added to put the same array to a different array index?
看看这个,告诉我我想念的是什么
推荐答案数组中的数据被覆盖,因为每次遇到 $ key 时,都要重新分配它的值.
The data in the array is being overwritten because you are reassigning the value of $key each time it is encountered.
您想要做的是创建一个辅助数组作为 $ key 值,然后将节点推入该数组中,这样您就可以得到预期的结果.
What you want to do is create a secondary array as the $key value and push nodes into that array this way you end up with your expected result.
[ 'NM1' => ['...', '...'], 'PR1' => ['...', '...'] ]代码应该是
while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE) { $key = array_shift($row); // Notice the extra [] $data[$key][] = $row; }每个键现在将包含一个数组,每个遇到的行都有一个节点.
Each key will now contain an array with a node for each row encountered.
更多推荐
防止数组覆盖,而是创建新的数组索引
发布评论