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

标签 php csv sorting header

我的 CSV 文件如下所示:


|标题一|标题 b |标题c |


|第 1234 章3 | AB 10 |


| 5678 | 5 | AB 9 |

我需要的是保留标题并按标题 c 对其他行进行排序。

到目前为止我做了什么。

{$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);
}

最佳答案

$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;

这输出

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"
  }
}

现场演示 ( https://eval.in/836000 )

试试这两个函数

/**
 * 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;
}

此版本的函数将字符串而不是文件作为输入(您可以将它们组合在一个函数中并更改输入,因为大多数过程几乎相同)

/**
 * 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;
}

关于php - 如何使用 PHP 对 CSV 文件进行排序而不对标题行进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45248143/

相关文章:

php - 使用过多内存问题的 Doctrine 事务

php - 使用 PHP 通过 SSH 连接到 MySQL

java - 根据对象列表中列表中的字段对对象列表进行排序

python - 按两个标准对数组进行排序

php - 使用 WHERE 子句检查一个 SQL 查询中的数组中的值

PHP文件不会复制

php - 加载数据 Infile OPTIONALLY ENCLOSED BY 未按预期工作

php - 在本地和实时之间同步数据库,php mysql

python - Pandas - 使用数据框值作为字符串填充列表

arrays - Swift:使用备用键的合并排序算法