dongli564510 2017-08-18 06:55
浏览 33
已采纳

执行包含字母数字元素php的数组的排序

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?

  • 写回答

1条回答 默认 最新

  • doubianxian6557 2017-08-18 08:47
    关注

    So I explode the words in to two new arrays and sort them with multisort and year as the leading array.
    Then I rebuild the new result array.

    $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);
    

    https://3v4l.org/eCi7J

    EDIT; I use a temp array to hold the exploded values and use array_splice and implode to build fruits, and separate the year.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化