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

时间:2016-09-18 00:56:31

标签: php arrays sorting

我正在尝试将包含下划线_的字符串移动到数组的底部。我假设usort()是最好的方法,但不知道如何以最有效的方式做到这一点。假设我的数组是'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 (){...});

更新:我想我找到了办法:

$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);

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我相信你可以找到usort()的方法,但是快速做到这一点的方法就是将数组分成两部分,然后将它们组合起来:

<?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));

给你:

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
)