我通过以下方式将数据存储在平面文件中:
1|$item|$price|$quality|$keywords
现实中是这样的:
1|Shoes|50|5|Classy,basic
3|Shirt|25|4|Simple
2|Tshirt|20|1|Basic, urban
4|Coat|45|3|Classy, preppy
我正在尝试按我选择的列之一对数据进行排序,比方说按价格。这是由 ajax 函数调用的文件,其中列出了数据:
$cat_file = "data.php";
$cat_db = file("$cat_file");
$call = fopen("$cat_file","r");
foreach($cat_db as $cat_line) {
$cat_line_arr = explode("|",$cat_line);
$cat_line_id = $cat_line_arr[1];
if($cat_line_id == $cat) {
$id = $cat_line_arr[0];
$item = $cat_line_arr[1];
$price = $cat_line_arr[2];
$quality = $cat_line_arr[3];
$keywords = $cat_line_arr[4];
if (BLABLABLACONDITION) {
*LISTS THE DATA SORTED THE WAY I WANT*
}
}
}
fclose($call);
我上面的代码工作正常,但没有特定的排序,它只是按照文件中的原始顺序列出数据。 例如,如果按价格和降序排序,我想要得到的结果是:
1|Shoes|50|5|Classy,basic
4|Coat|45|3|Classy, preppy
3|Shirt|25|4|Simple
2|Tshirt|20|1|Basic, urban
我应该用什么替换按我想要的方式列出数据来对数据进行排序?预先感谢您的帮助
最佳答案
// read file as string and turn into an array, 1 element per line
$records = explode("\n", file_get_contents('path/to/file'));
// turn each line into an array, 1 element per field
array_walk($records, function (&$record) { $record = explode('|', $record); });
//$records is now a two-dimensional array containing the data
// gather the prices into a new array
$prices = array_map(function ($record) { return (int) $record[2]; }, $records);
// use the prices to sort the records
array_multisort($prices, SORT_ASC, $records);
foreach ($records as $record) {
//... do your thing.
}
关于php - 按列对平面文件中的数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713173/