user4724553
user4724553

Reputation:

Re arranging the columns in csv file in php

I m reading a csv file and updating the csv file and saving it.I want to rearrange the columns in new file like after second column i want to add tenth column before third ,but when i m trying to do that its replacing the second column with tenth column not adding that after second one.Following is the code

<?php
$inFile='file.csv';
$outFile='file_updated.csv';
$read = fopen($inFile, 'r');
$write = fopen($outFile, 'w');
if ($write && $read) {
    while (($data = fgetcsv($read)) !== FALSE) {
        unset($data[1]);
        $data[2]=$data[10];
        fputcsv($write, $data);
    }
}
fclose($write);
fclose($read);
?>

Upvotes: 0

Views: 1722

Answers (1)

cwurtz
cwurtz

Reputation: 3257

Why not make an array of the order you want it to be after and then build a new data array to write.

$order = array(1,2,10,3,4,5,6,7,8,9);
while (($data = fgetcsv($read)) !== FALSE) {
    $new = array();
    foreach($order as $index)
        $new[] = $data[$index];
    fputcsv($write, $new);
}

Upvotes: 1

Related Questions