防止数组覆盖,而是创建新的数组索引

编程入门 行业动态 更新时间:2024-10-24 20:11:58
本文介绍了防止数组覆盖,而是创建新的数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文件,我需要将文件的内容保存在我的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.

更多推荐

防止数组覆盖,而是创建新的数组索引

本文发布于:2023-11-22 18:25:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618516.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!