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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用