将数据附加到csv的中间行/行,而不是最后一行或行 [英] Append data to middle line/row of a csv instead of the last line or row

查看:228
本文介绍了将数据附加到csv的中间行/行,而不是最后一行或行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些记录的csv文件,每个记录都有唯一的ID。我运行一个循环来找到唯一的ID,然后附加一些更多的数据到该记录。

I have a csv file with some records and each record has unique ID. I'm running a loop to find that unique ID and then append some more data to that record.

有没有临时文件可以做到这一点?创建此类文件并移动其中的所有数据需要更多时间...

Is it possible to do this without a temporary file? Creating such file and moving all data in it takes more time...

我的代码是:

<?php 
$temp = fopen('tempwin.csv','w+');

if (($handle = fopen("win.csv", "r+")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;

        for ($c=0; $c < $num; $c++) {                        
            if($data[4] == trim($leadid)){
                $data[5] = trim($_POST['year']);
                $data[6] = trim($_POST['make']);
                $data[7] = trim($_POST['model']);
                $data[8] = trim($_POST['trade']);
            }
        }

        fputcsv($temp, $data);
    }

    fclose($handle);
    fclose($temp);
}

unlink('win.csv');
rename('tempwin.csv','win.csv');


推荐答案

您可以使用以下内容,但您需要通过

You can use following, but you need to pass the row number i.e where you need to add row.

<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
    $array2 = array_splice($array, $pos);
    $array[] = $val;
    $array = array_merge($array, $array2);

    return $array;
}

//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;

//Full path & Name of the CSV File
$FileName = 'data.csv';

//Read the file and get is as a array of lines.
$arrLines = file($FileName);

//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);

//Convert result array to string.
$ResultStr = implode("\n", $Result);

//Write to the file.
file_put_contents($FileName, $ResultStr);
?>

这篇关于将数据附加到csv的中间行/行,而不是最后一行或行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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