简体   繁体   English

如何在php中按其值排序和排列

[英]How would I sort and array by its values in php

I have this array called $csv, it contains cars that have year, make and model. 我有一个名为$ csv的数组,它包含具有年份,品牌和型号的汽车。

function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
    $line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}


// Set path to CSV file
$csvFile = 'csv/file.csv';
$csv = readCSV($csvFile);
array_shift($csv); 

foreach($csv as $car){

$year = $car[3];
$make = $car[4];
$model = $car[5];

echo $year;
}

This gives me - 2011 2009 2012 2012 2013 这给了我-2011 2009 2012 2012 2013

How would I filter the results to display in order by newest to oldest? 我将如何过滤结果以从新到旧的顺序显示?

$years = [];
foreach($csv as $car){
    $years[] = $car[3];
}

rsort($years);

foreach($years as $year) {
    echo $year;
}

If you need low-to-high sorting use sort instead of rsort. 如果需要从低到高排序,请使用sort而不是rsort。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM