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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里