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

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

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 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?