英文:
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,"","",abc
suse,134,"","",bca
or become this (whichever is easier)
name,phone,city,postcode,address
john,123,city,postcode,abc
suse,134,city,postcode,bca
I did
<?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>";
?>
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("{$filename}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
array_splice($data, 2, 0, ['city', 'postcode']);
$the_big_array[] = $data;
}
fclose($h);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论