gpt4 book ai didi

php - 使用 php 在 csv 文件中添加 2 个新列标题和内容

转载 作者:行者123 更新时间:2023-12-02 07:42:05 25 4
gpt4 key购买 nike

我有一个包含以下值的现有 csv 文件

column1 column2
Fr-fc Fr-sc
Sr-fc Sr-sc

我想在其中添加 2 个新列并实现以下格式

column1 column2 column3 column4
Fr-fc Fr-sc 1 2
Sr-fc Sr-sc 1 2

如果我使用以下代码,它将在新创建的列的列数据中插入相同的列标题值

$a = file('amit.csv');// get array of lines
$new = '';
foreach($a as $line){
$line = trim($line);// remove end of line
$line .=";column3";// append new column
$line .=";column4";// append new column
$new .= $line.PHP_EOL;//append end of line
}
file_put_contents('amit2.csv', $new);// overwrite the same file with new data

如何实现上述目标?

最佳答案

这种方法代码较少

<?php
$inFile = fopen('test.csv','r');
$outFile = fopen('output.csv','w');

$line = fgetcsv($inFile);
while ($line !== false) {
$line[] = 'third column';
$line[] = 'fourth column';
fputcsv($outFile, $line);
$line = fgetcsv($inFile);
}
fclose($inFile);
fclose($outFile);

关于php - 使用 php 在 csv 文件中添加 2 个新列标题和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36142899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com