如何使用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);
}

展开翻译

译文

我的CSV文件如下所示:</ p>


| 标题a 标题b | title c | </ h2>


| 1234 | 3 | AB 10 | </ h2>


| 5678 | 5 | AB 9 | </ h2>

我需要的是保持标题并按标题c排序其他行。</ p>

到目前为止我做了什么。 / p>

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

\ nforeach($ file as $ key =&gt; $ val){
//由comma爆炸
$ rowarray = explode(“,”,$ val);

//只获取第二列
$ rows [] = $ rowarray [2];
}

//按名称排序
natsort($ rows);

// //将结果借助键放到输出数组
foreach( $ rows为$ key =&gt; $ val){
$ resultstring。= trim($ file [$ key])。 “
”;
}

//显示结果
// echo $ resultstring;

file_put_contents(“output.csv”,$ resultstring);
}
</ code > </ pre>
</ div>

drau67562
drau67562 简单地说,排除第一行的处理!
2 年多之前 回复

1个回答

$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;
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!