douren7921 2017-07-21 23:34
浏览 99

如何使用PHP对CSV文件进行排序而不对标题行进行排序?

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]) . "
";
}

// show the result
//echo $resultstring;

file_put_contents("output.csv", $resultstring);
}
  • 写回答

1条回答

  • drsw9390405 2017-07-22 01:02
    关注
    $fakeCsvFile = '"titleA","titleB","titleC"'      ."
    ".
                    '"1234","3","AB 10"'             ."
    ".
                    '"5678","5","AB 9'               ."
    ";
    //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, "
    ");
        $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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的