duanlu4371 2016-09-18 00:56
浏览 21
已采纳

重新排序数组,将包含下划线的所有字符串移动到底部

I am trying to move the strings that contain an underscore _ to the bottom of my array. I'm assuming usort() is the best way but not sure how to do this in the most efficient way. Let's say my array is '1','34_1','35_1','36_1','7','41_4','38_5','5','41_5','44_5','45_5'

usort(['1','34_1','35_1','36_1','7','41_4','38_5','5','41_5','44_5','45_5'], function (){...});

UPDATE: I think I found a way to do it:

$myarray = ['1','34_1','35_1','36_1','7','41_4','38_5','5','41_5','44_5','45_5'];

function sortem($myarray) {
    foreach ($myarray as $index=>$item)
    {
        if (preg_match('/^_+$/', $item))
        {
            unset($myarray[$index]);
            $myarray[$index] = $item;               
        }
    }
}
usort($myarray, "sortem");
$tagsuri = array_reverse($tagsuri);

Is there a better way?

  • 写回答

1条回答 默认 最新

  • dongyongkui6329 2016-09-18 04:25
    关注

    I am sure you could find a way to usort() but a quick way to do this would just be to split the array into two, then combine them back:

    <?php
    $myarray = array('1','34_1','35_1','36_1','7','41_4','38_5','5','41_5','44_5','45_5');
    
    foreach($myarray as $value) {
        # Put all numbers into one array, underscored into a second
        if(strpos($value,'_') !== false)
            $strArr[]   =   $value;
        else
            $numArr[]   =   $value;
    }
    # Sort both arrays
    # You'll probably want to do checks to see that they are not empty first
    asort($strArr);
    asort($numArr);
    # Combine arrays
    print_r(array_merge($numArr,$strArr));
    

    Gives you:

    Array
    (
        [0] => 1
        [1] => 5
        [2] => 7
        [3] => 34_1
        [4] => 35_1
        [5] => 36_1
        [6] => 38_5
        [7] => 41_4
        [8] => 41_5
        [9] => 44_5
        [10] => 45_5
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站