使用php在csv文件中添加2个新的列标题和内容 [英] Add 2 new column header and contents in csv file using php

查看:166
本文介绍了使用php在csv文件中添加2个新的列标题和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已有一个具有以下值的csv文件

I've an existing csv file with following values

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

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

I want to add 2 new columns in it and achieve the following format

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

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

If I use following code it inserts same column header value in column data for the newly created columns

$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内置的csv函数 fgetcsv fputcsv 可以简化您的工作。首先使用 fgetcsv 读取每一行,并将数据存储在多维数组中:

Instead of reinventing the wheel, you can use php's inbuilt csv functions fgetcsv and fputcsv respectively to ease your work. First read in each row with fgetcsv and store the data in a multidimensional array:

$delimiter = "\t"; //your column separator
$csv_data = array();
$row = 1;
if (($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        $csv_data[] = $data;
        $row++;
    }
    fclose($handle);
}

下一步,使用 array_merge

$extra_columns = array('column3' => 1, 'column4' => 2);
foreach ($csv_data as $i => $data) {
    if ($i == 0) {
        $csv_data[$i] = array_merge($data, array_keys($extra_columns));
    } else {
        $csv_data[$i] = $data = array_merge($data, $extra_columns);
    }
}

最后使用 fputcsv 将每一行输入到csv中。

Finally use fputcsv to enter each row into the csv.

if (($handle = fopen('test.csv', 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}

您可以结合使用以下步骤来减少代码数量,从而提高代码效率循环。

You can combine these steps to make your code more efficient by reducing the number of loops.

这篇关于使用php在csv文件中添加2个新的列标题和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆