如何按特定列对PHP中的CSV表数据进行排序? [英] How to sort CSV table data in PHP by a specific column?
本文介绍了如何按特定列对PHP中的CSV表数据进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是CSV表:
-------------------------
| Name | Age | Favorite |
-------------------------
| John | 30 | Apple |
-------------------------
| Bill | 25 | Grape |
-------------------------
| Ann | 40 | Orange |
-------------------------
现在,严格使用PHP,是否仍然可以通过按年龄"的升序仅对收藏夹"进行排序?预期的输出将是这样的:
Now, using strictly PHP, is there anyway to sort only the "Favorite" by ascending order of "Age"? An expected output would be something like this:
25 Grape
30 Apple
40 Orange
我一直在使用fgetcsv
将它们回显到文档上,但是,当然,它们不是按升序排序的.无论如何,是否可以将它们放入数组或其他东西中,按年龄排序,然后回显?
I've been using fgetcsv
to echo them onto the document, but they are not not sorted by ascending age, of course. Is there anyway to throw these in an array or something, sort by age, and then echo?
推荐答案
打开CSV文件:
function readCSV($file)
{
$row = 0;
$csvArray = array();
if( ( $handle = fopen($file, "r") ) !== FALSE ) {
while( ( $data = fgetcsv($handle, 0, ";") ) !== FALSE ) {
$num = count($data);
for( $c = 0; $c < $num; $c++ ) {
$csvArray[$row][] = $data[$c];
}
$row++;
}
}
if( !empty( $csvArray ) ) {
return array_splice($csvArray, 1); //cut off the first row (names of the fields)
} else {
return false;
}
}
$csvData = readCSV($csvPath); //This is your array with the data
然后,您可以使用 array_multisort()对其进行排序值.
Then you could use array_multisort() to sort it on a value.
<?php
// Obtain a list of columns
foreach ($csvData as $key => $row) {
$age[$key] = $row['volume'];
$favorite[$key] = $row['edition'];
}
// Sort the data with age first, then favorite
// Add $csvData as the last parameter, to sort by the common key
array_multisort($age, SORT_ASC, $favorite, SORT_ASC, $csvData);
?>
这篇关于如何按特定列对PHP中的CSV表数据进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文