PHP – 在现有数据之间插入新列到CSV文件中

huangapple go评论121阅读模式
英文:

PHP - Insert new column to CSV in between existing data

问题

我有以下内容的details.csv文件:

  1. name,phone,address
  2. john,123,abc
  3. suse,134,bca

我想要插入空的新列,使其变成以下之一:

  1. name,phone,city,postcode,address
  2. john,123,"","abc"
  3. suse,134,"","bca"

或者变成这个(哪个更容易实现):

  1. name,phone,city,postcode,address
  2. john,123,city,postcode,abc
  3. suse,134,city,postcode,bca

我尝试了以下代码:

  1. <?php
  2. $filename = 'details.csv';
  3. $the_big_array = [];
  4. if (($h = fopen("{$filename}", "r")) !== FALSE)
  5. {
  6. while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
  7. {
  8. $data[] = 'city';
  9. $data[] = 'postcode';
  10. $the_big_array[] = $data;
  11. }
  12. fclose($h);
  13. }
  14. echo "<pre>";
  15. var_dump($the_big_array);
  16. echo "</pre>";
  17. ?>

但我得到了以下结果:

  1. name,phone,address,city,postcode
  2. john,123,abc,city,postcode
  3. suse,134,bca,city,postcode

请帮忙解决。

英文:

I have details.csv with following content:

  1. name,phone,address
  2. john,123,abc
  3. suse,134,bca

I want to insert empty new columns so it will become:

  1. name,phone,city,postcode,address
  2. john,123,&quot;&quot;,&quot;&quot;,abc
  3. suse,134,&quot;&quot;,&quot;&quot;,bca

or become this (whichever is easier)

  1. name,phone,city,postcode,address
  2. john,123,city,postcode,abc
  3. suse,134,city,postcode,bca

I did

  1. &lt;?php
  2. $filename = &#39;details.csv&#39;;
  3. $the_big_array = [];
  4. if (($h = fopen(&quot;{$filename}&quot;, &quot;r&quot;)) !== FALSE)
  5. {
  6. while (($data = fgetcsv($h, 1000, &quot;,&quot;)) !== FALSE)
  7. {
  8. $data[] = &#39;city&#39;;
  9. $data[] = &#39;postcode&#39;;
  10. $the_big_array[] = $data;
  11. }
  12. fclose($h);
  13. }
  14. echo &quot;&lt;pre&gt;&quot;;
  15. var_dump($the_big_array);
  16. echo &quot;&lt;/pre&gt;&quot;;
  17. ?&gt;

But I got this instead:

  1. name,phone,address,city,postcode
  2. john,123,abc,city,postcode
  3. suse,134,bca,city,postcode

Help please..

答案1

得分: 3

你可以使用 array_splice()

https://www.php.net/manual/en/function.array-splice.php

  1. if (($h = fopen("{$filename}", "r")) !== false) {
  2. while (($data = fgetcsv($h, 1000, ",")) !== false) {
  3. array_splice($data, 2, 0, ['city', 'postcode']);
  4. $the_big_array[] = $data;
  5. }
  6. fclose($h);
  7. }
英文:

You can use array_splice()

https://www.php.net/manual/en/function.array-splice.php

  1. if (($h = fopen(&quot;{$filename}&quot;, &quot;r&quot;)) !== false) {
  2. while (($data = fgetcsv($h, 1000, &quot;,&quot;)) !== false) {
  3. array_splice($data, 2, 0, [&#39;city&#39;, &#39;postcode&#39;]);
  4. $the_big_array[] = $data;
  5. }
  6. fclose($h);
  7. }

huangapple
  • 本文由 发表于 2023年7月10日 15:27:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定