1

我有一个数组,其键的格式为 [A1] -> [A20]、[B1] -> [B20] 等,我正在尝试使用 first 对该数组进行排序ksort()(以正确的顺序获取字母) 然后uksort().

但是,我不知道uksort()应该如何编写函数,并且我的数组键以奇怪的顺序返回。有人可以看看我做错了什么并提出建议吗?谢谢。

function _sort_selection_keys($a, $b){

    $let_a = substr($a, 0, 1);
    $let_b = substr($b, 0, 1);
    $num_a = intval(substr($a, 1));
    $num_a = intval(substr($b, 1));

    /** Check that the first letter is the same. It should be, as the array has already been through 'ksort()', but it's worth checking any way */
    if($let_a !== $let_b) :
        return strcasecmp($a, $b);
    endif;

    if($num_a > $num_b) :
        return -1;
    elseif($num_a = $num_b) :
        return 0;
    elseif($num_a < $num_b) :
        return 1;
    endif;

}
4

5 回答 5

4

You could just use the strnatcmp function which will fit your needs:

uksort($array, 'strnatcmp');

And another solution metioned by @M8R-1jmw5r

ksort($array, SORT_NATURAL);

于 2013-04-10T15:55:42.107 回答
1

如果不在那里调试您的代码,您可以使用 'strnatcmp' 的内置功能uksort对键进行字母数字排序。

未排序的数组代码

$array = array(
    'A1' => array(),
    'A2' => array(),
    'A3' => array(),
    'A4' => array(),
    'C1' => array(),
    'B2' => array(),
    'B1' => array(),
    'D1' => array(),
    'C2' => array(),
    'B3' => array(),
    'D3' => array(),
    'D2' => array(),
);

uksort($array, 'strnatcmp');

var_dump($array);

结果

array (size=12)
  'A1' => 
    array (size=0)
      empty
  'A2' => 
    array (size=0)
      empty
  'A3' => 
    array (size=0)
      empty
  'A4' => 
    array (size=0)
      empty
  'B1' => 
    array (size=0)
      empty
  'B2' => 
    array (size=0)
      empty
  'B3' => 
    array (size=0)
      empty
  'C1' => 
    array (size=0)
      empty
  'C2' => 
    array (size=0)
      empty
  'D1' => 
    array (size=0)
      empty
  'D2' => 
    array (size=0)
      empty
  'D3' => 
    array (size=0)
      empty
于 2013-04-10T15:56:58.287 回答
1

根据以下文档usort

如果认为第一个参数分别小于、等于或大于第二个参数,则比较函数必须返回一个小于、等于或大于零的整数。

也就是说,而不是返回trueor false,您应该返回$num_a - $num_b(或进行比较并返回-1, 1, or 0.

于 2013-04-10T15:52:12.040 回答
1

First, I think all you need to do is change your second "$num_a" line to "$num_b". Other than that, I would simply use strnatcasecmp() on the keys instead of all the dissecting you are attempting.

于 2013-04-10T15:54:25.143 回答
1

您想按自然顺序按键对数组进行排序:

ksort($array, SORT_NATURAL);

ksort()

自然排序顺序为:

regular:  A1, A10, A11, A2, A20, A21, ... A3, ...
natural:  A1, A2, A3, ..., A10, A11, ... A20, A21 
于 2013-04-10T16:02:15.550 回答