3

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 Answers1

0
$fakeCsvFile = '"titleA","titleB","titleC"'      ."\n".
                '"1234","3","AB 10"'             ."\n".
                '"5678","5","AB 9'               ."\n";
//function sortCSVString($string, $columnToSortByIndex = 0, $asc = true )
var_dump(sortCSVString($fakeCsvFile,2,false));
exit;

This outputs

array(3) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "titleA"
    [1]=>
    string(6) "titleB"
    [2]=>
    string(6) "titleC"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "5678"
    [1]=>
    string(1) "5"
    [2]=>
    string(4) "AB 9"
  }
  [2]=>
  array(3) {
    [0]=>
    string(4) "1234"
    [1]=>
    string(1) "3"
    [2]=>
    string(5) "AB 10"
  }
}

Live demo (https://eval.in/836000)

Try these 2 functions

/**
 * sort an CSV file and return the sorted data in array
 * @param string $file name
 * @param number $columnToSortByIndex
 * @param bool $asc
 * @return array
 */
function sortCSVFile($file, $columnToSortByIndex = 0, $asc = true )
{
    //1- prepare data
    $csvArray = array_map('str_getcsv', file($file));
    if(!$csvArray) return [];
    // 2- save the header
    $header = $csvArray[0];
    // 3- sort
    array_shift($csvArray);
    $cTiteles = [];
    foreach ($csvArray as $row){
        $cTiteles[] = $row[$columnToSortByIndex];
    }
    //the sorting has been taken from here
    //https://stackoverflow.com/a/1598385/5407848
    if($asc){
        array_multisort($cTiteles, SORT_ASC, $csvArray);
    }else{
        array_multisort($cTiteles, SORT_DESC, $csvArray);
    }
    // 3- prepend the header again
     array_unshift($csvArray,$header);
     return $csvArray;
}

This version of the function takes string as input instead of file (you can combine them in 1 function and change the input as most of the procedures are almost the same)

/**
 * sort an CSV string and return the sorted data in array
 * @param string $file name
 * @param number $columnToSortByIndex
 * @param bool $asc
 * @return array
 */
function sortCSVString($string, $columnToSortByIndex = 0, $asc = true )
{
    //1- prepare data
    $csvRows = str_getcsv($string, "\n");
    $csvArray = [];
    // the workaround in here has been inspired from here
    //http://php.net/manual/en/function.str-getcsv.php#Hcom101888
    foreach($csvRows as $row){
        $row = str_getcsv($row, ",");
        $csvArray[] = $row;
    }
    if(!$csvArray) return [];
    // 2- save the header
    $header = $csvArray[0];
    // 3- sort
    array_shift($csvArray);
    $cTiteles = [];
    foreach ($csvArray as $row){
        $cTiteles[] = $row[$columnToSortByIndex];
    }
    if($asc){
        array_multisort($cTiteles, SORT_ASC, $csvArray);
    }else{
        array_multisort($cTiteles, SORT_DESC, $csvArray);
    }
    // 3- prepend the header again
     array_unshift($csvArray,$header);
     return $csvArray;
}
Accountant م
  • 6,975
  • 3
  • 41
  • 61