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

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

PHP - Insert new column to CSV in between existing data

问题

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

name,phone,address
john,123,abc
suse,134,bca

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

name,phone,city,postcode,address
john,123,"","abc"
suse,134,"","bca"

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

name,phone,city,postcode,address
john,123,city,postcode,abc
suse,134,city,postcode,bca

我尝试了以下代码:

<?php
$filename = 'details.csv';
$the_big_array = [];

if (($h = fopen("{$filename}", "r")) !== FALSE)
{
  while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
  {
  $data[] = 'city';
  $data[] = 'postcode';

    $the_big_array[] = $data;
  }

  fclose($h);
}

echo "<pre>";
var_dump($the_big_array);
echo "</pre>";
?>

但我得到了以下结果:

name,phone,address,city,postcode
john,123,abc,city,postcode
suse,134,bca,city,postcode

请帮忙解决。

英文:

I have details.csv with following content:

name,phone,address
john,123,abc
suse,134,bca

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

name,phone,city,postcode,address
john,123,&quot;&quot;,&quot;&quot;,abc
suse,134,&quot;&quot;,&quot;&quot;,bca

or become this (whichever is easier)

name,phone,city,postcode,address
john,123,city,postcode,abc
suse,134,city,postcode,bca

I did

&lt;?php
$filename = &#39;details.csv&#39;;
$the_big_array = [];

if (($h = fopen(&quot;{$filename}&quot;, &quot;r&quot;)) !== FALSE)
{
  while (($data = fgetcsv($h, 1000, &quot;,&quot;)) !== FALSE)
  {
  $data[] = &#39;city&#39;;
  $data[] = &#39;postcode&#39;;

    $the_big_array[] = $data;
  }

  fclose($h);
}

echo &quot;&lt;pre&gt;&quot;;
var_dump($the_big_array);
echo &quot;&lt;/pre&gt;&quot;;
?&gt;

But I got this instead:

name,phone,address,city,postcode
john,123,abc,city,postcode
suse,134,bca,city,postcode

Help please..

答案1

得分: 3

你可以使用 array_splice()

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

if (($h = fopen("{$filename}", "r")) !== false) {
    while (($data = fgetcsv($h, 1000, ",")) !== false) {
        array_splice($data, 2, 0, ['city', 'postcode']);

        $the_big_array[] = $data;
    }

    fclose($h);
}
英文:

You can use array_splice()

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

if (($h = fopen(&quot;{$filename}&quot;, &quot;r&quot;)) !== false) {
    while (($data = fgetcsv($h, 1000, &quot;,&quot;)) !== false) {
        array_splice($data, 2, 0, [&#39;city&#39;, &#39;postcode&#39;]);

        $the_big_array[] = $data;
    }

    fclose($h);
}

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:

确定