doumen6532 2015-03-03 15:14
浏览 270
已采纳

通过排序将数组元素移动到数组的末尾

If I have an array like so (it could be any combination of numbers):

$arr = array(1, 2, 4, 2, 3, 5, 4, 2, 1);

I want to move all the elements that equal 4 to the end of the array, while preserving the order of the other elements, so ideally my resulting array would be:

1, 2, 2, 3, 5, 2, 1, 4, 4

I thought I could acheve this by using a sort function:

uasort($arr, function($a, $b){
    return $b == 4 ? -1 : 1;
});

Which moves the "4" elements to the end, but ruins the order of the other elements, this is my result with the above code:

2, 3, 1, 2, 5, 2, 1, 4, 4

How should my sorting handler function look? / Is there a better way to achieve this than sorting the array?

Note; I want to preserve my array keys (hence uasort)

eval.in

  • 写回答

4条回答 默认 最新

  • duanhe4267 2015-03-03 15:46
    关注

    Here's one way to do it with uasort:

    $arr = array(1, 2, 4, 2, 3, 5, 4, 2, 1);
    
    uasort($arr, function($a, $b){
        if ($a == 4) return -1;
        if ($b == 4) return 1;
        return 0;
    });
    
    $arr = array_reverse($arr, true);
    
    print_r($arr);
    

    The true argument to array_reverse preserves the keys in the array. The return 0 is optional but improves clarity in my opinion.

    Output:

    Array
    (
        [0] => 1
        [3] => 2
        [1] => 2
        [4] => 3
        [5] => 5
        [7] => 2
        [8] => 1
        [2] => 4
        [6] => 4
    )
    

    The fact that some of the keys corresponding to the same value are mixed up is unavoidable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?