How to sort CSV files using PHP whitout sort the header line?

Viewed 1029

My CSV file looks like this:


| title a | title b | title c |


| 1234 | 3 | AB 10 |


| 5678 | 5 | AB 9 |

What i need to is keep the header and sort the others rows order by title c.

what i did so far.

{$rows = array();
$resultstring = "";
$file = file("input.csv");



foreach($file as $key => $val){
    // explode by comma
    $rowarray = explode(",",$val);

    // get only the second column
    $rows[] = $rowarray[2];
}

// sort by names
natsort($rows);

// put the result with the help of the key to output array
foreach($rows as $key => $val){
    $resultstring .= trim($file[$key]) . "\r\n";
}

// show the result
//echo $resultstring;

file_put_contents("output.csv", $resultstring);
}
1 Answers
Related