PHP -在现有数据之间插入新列到CSV

gojuced7  于 2023-07-31  发布在  PHP
关注(0)|答案(1)|浏览(84)

我有详细信息.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


救命啊...

hk8txs48

hk8txs481#

可以使用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);
}

字符串

相关问题