在多维字母数字数组(数字优先)上使用 usort()

Using usort() on multidimensional alphanumeric array (numbers first)

这是我尝试排序的示例数组:

$array = (object)array(

    'this' => 'that',
    'posts'=> array(
        'title' => '001 Chair',
        'title' => 'AC43 Table',
        'title' => '0440 Recliner',
        'title' => 'B419',
        'title' => 'C10 Chair',
        'title' => '320 Bed',
        'title' => '0114'
    ),
    'that' => 'this'
);

usort($array->posts, 'my_post_sort');

这是我用来排序的函数:

function my_post_sort($a, $b) {

    $akey = $a->title;
    if (preg_match('/^[0-9]*$',$akey,$matches)) {
      $akey = sprintf('%010d ',$matches[0]) . $akey;
    }
    $bkey = $b->title;
    if (preg_match('/^[0-9]*$',$bkey,$matches)) {
      $bkey = sprintf('%010d ',$matches[0]) . $bkey;
    }

    if ($akey == $bkey) {
      return 0;
    }

    return ($akey > $bkey) ? -1 : 1;
}

这给了我以下结果:

'posts', array(
    'title' => 'C10 Chair',
    'title' => 'B419',
    'title' => 'AC43 Table',
    'title' => '320 Bed',
    'title' => '0440 Recliner',
    'title' => '0114',
    'title' => '001 Chair'
)

现在,我需要的最后一步是让数字(降序)出现在字母(降序)之前。

这是我的期望的输出:

'posts', array(
    'title' => '320 Bed',
    'title' => '0440 Recliner',
    'title' => '0114',
    'title' => '001 Chair',
    'title' => 'C10 Chair',
    'title' => 'B419',
    'title' => 'AC43'
)

我尝试了各种排序、uasorts、preg_match和其他函数;似乎无法弄清楚最后一步。

有什么建议或帮助吗?谢谢。

首先,我不认为你的数组可以工作......你不能在同一数组级别上多次使用相同的键。

foreach ($array as $key => $title) {

        if ( is_numeric(substr($title, 0, 1)) ) {
            $new_array[$key] = $title;
        }
    }

    array_multisort($array, SORT_DESC, SORT_STRING);
    array_multisort($new_array, SORT_DESC, SORT_NUMERIC);
    $sorted_array = array_merge($array, $new_array);

试试这个比较函数:

function my_post_sort($a, $b) {

    $akey = $a->title;
    $bkey = $b->title;

    $diga = preg_match("/^[0-9]/", $akey);
    $digb = preg_match("/^[0-9]/", $bkey);

    if($diga && !$digb) {
        return -1;
    }

    if(!$diga && $digb) {
        return 1;
    }

    return -strcmp($akey, $bkey);
}

它将按降序排序,但会将数字放在其他符号之前。