嗨,我有一个类似
的数组$test = ['orange 2016','orange 2017' ,'Mango 2018' ,'apple 2018' ,'apple 2015'];
我必须对数组进行排序,以便数组相对于年份应该是降序。我尝试了不同类型的排序。但都失败了。我的预期结果如下所示
$test = ['apple 2018','Mango 2018','Orange 2017','Orange 2016' ,'apple 2015'];
我的代码在下面分享
$test = ['jan 2016','jan 2017' ,'Dec 2018' ,'April 2018' ,'March 2015'];
echo "<pre>";
print_r($test);
echo "</pre>";
$n = count($test);
for($i=0;$i<$n;$i++){
for($j=$i+1;$j<($n);$j++){
preg_match('#(\d+)$#',$test[$i],$year_one);
preg_match('#(\d+)$#',$test[$j],$year_two);
if($year_one[1] < $year_two[1]){
$temp = $test[$j];
$test[$j] = $test[$i];
$test[$i] = $temp;
}
if($year_one[1] == $year_two[1]){
if(strcmp($test[$j],$test[$i]) < 0 ){
$temp = $test[$j];
$test[$j] = $test[$i];
$test[$i] = $temp;
}
}
}
}
echo "<pre>";
print_r($test);
echo "</pre>";
这是一个很复杂的代码。是否有其他最简单的方法可以达到预期的效果?
答案 0 :(得分:1)
因此,我将这些单词分解为两个新数组,并使用multisort和year作为前导数组进行排序 然后我重建新的结果数组。
$test = ['Red orange 2016','orange 2017' ,'Mango 2018' ,'Granny Smith apple 2018' ,'apple 2015'];
$a = array(); // create two new arrays to hold fruit and year
$b = array();
$temp = array();
foreach($test as $item){
$temp = explode(" ", $item); // explode the fruit/year to temp array
$a[] = implode(" ", array_splice($temp, 0, -1)); // implode all but the last item as "fruit"
$b[] = end($temp); // last item is the year
}
array_multisort($b, $a); // sort the new arrays
$result=array();
for($i=count($b)-1; $i>=0; $i--){ // looping backwards to only count() once. (faster)
$result[] = $a[$i] . " " . $b[$i]; // rebuild the new array with correct sorting.
}
var_dump($result);
EDIT;我使用临时数组来保存爆炸值,并使用array_splice和implode来构建水果,并将年份分开。