php - 按列对平面文件中的数据进行排序

标签 php arrays sorting netcat

我通过以下方式将数据存储在平面文件中:

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/

相关文章:

arrays - 获取数组中 NSButton 的索引并将它们附加到 swift (Cocoa) 中的整数数组

c# - 在 C# 中将一维数组转换为二维数组以获取 AES 数据矩阵

perl - 在哈希 perl 数组中按数字和字母顺序对数字和字符串进行排序

java - java中Akka流按id排序

php - 用于模拟由新类对象调用的方法的单元测试

javascript - 如何从使用 javascript 发布的表单中获取值

php - 使用php在不同的sql表中导入csv文件的选定列

php - 如何访问嵌套数组值

bash - 在同一行 Bash 上排序

php - 如何使用 Yii2 ActiveRecord 更新多行?