Hi I have an array like
$test = ['orange 2016','orange 2017' ,'Mango 2018' ,'apple 2018' ,'apple 2015'];
I have to sort the array so that the array should be descending order with respect to the year.I tried with different type of sorting.But all fails.My expected result is something like below
$test = ['apple 2018','Mango 2018','Orange 2017','Orange 2016' ,'apple 2015'];
My code is shared below
$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>";
It is little complicated code.Is any other simplest method for achieving the desired result?