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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器