Re arranging the columns in csv file in php -
i m reading csv file , updating csv file , saving it.i want rearrange columns in new file after second column want add tenth column before third ,but when m trying replacing second column tenth column not adding after second one.following 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); ?>
why not make array of order want after , build new data array write.
$order = array(1,2,10,3,4,5,6,7,8,9); while (($data = fgetcsv($read)) !== false) { $new = array(); foreach($order $index) $new[] = $data[$index]; fputcsv($write, $new); }
Comments
Post a Comment