Perform sorting of array that contain alphanumeric elements php -


hi have array like

$test = ['orange 2016','orange 2017' ,'mango 2018' ,'apple 2018' ,'apple 2015']; 

i have sort array array should descending order respect year.i tried different type of sorting.but fails.my expected result below

$test = ['apple 2018','mango 2018','orange 2017','orange 2016' ,'apple 2015']; 

my code 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 little complicated code.is other simplest method achieving desired result?

so explode words in 2 new arrays , sort them multisort , year leading array.
rebuild new result array.

$test = ['red orange 2016','orange 2017' ,'mango 2018' ,'granny smith apple 2018' ,'apple 2015'];  $a = array(); // create 2 new arrays hold fruit , year $b = array(); $temp = array(); foreach($test $item){     $temp = explode(" ", $item); // explode fruit/year temp array     $a[] = implode(" ", array_splice($temp, 0, -1)); // implode last item "fruit"     $b[] = end($temp); // last item year }  array_multisort($b, $a); // sort new arrays  $result=array(); for($i=count($b)-1; $i>=0; $i--){ // looping backwards count() once. (faster)     $result[] = $a[$i] . " " . $b[$i]; // rebuild new array correct sorting. } var_dump($result); 

https://3v4l.org/eci7j

edit; use temp array hold exploded values , use array_splice , implode build fruits, , separate year.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -