在PHP中对多维关联数组进行排序

时间:2013-05-21 00:51:23

标签: php arrays sorting multidimensional-array

我有一个如下所示的PHP数组:

array (size=1)
  'Marriot' => 
    array (size=7)
      0 => string 'doc5.txt' (length=8)
      1 => string 'test.txt' (length=8)
      2 => string 'test1.txt' (length=9)
      3 => string 'test2.txt' (length=9)
      4 => string 'test3.txt' (length=9)
      5 => 
        array (size=1)
          'Special Docs' => 
            array (size=2)
              0 => string 'doc4.txt' (length=8)
              1 => string 'doc3.txt' (length=8)
      6 => 
        array (size=1)
          'ADocs' => 
            array (size=0)
              empty

如您所见,它包含非关联文件,然后是两个文件夹,“Special Docs”和“ADocs”。我的问题有两方面:

首先,我想将两个文件夹移动到数组的顶部,以便它们在我的视图中突出显示。其次,我想按字母顺序对文件夹进行排序(即将“ADocs”放在“特殊文档”之上。我尝试过array_multisort但没有成功,而且有点卡在这里。有人知道我怎么做到这一点吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

示例输入

$dir = array(
    0 => 'doc5.txt',
    1 => 'test.txt',
    2 => 'test1.txt',
    3 => 'test2.txt',
    4 => 'test3.txt',
    5 => array(
        'Special Docs' => array (
              0 => 'doc4.txt',
              1 => 'doc3.txt'
          )
    ),
    6 => array( 
        'ADocs' => array()
    )
);

1级排序

function cmp ($a,$b) {
    if (is_array($a)){
        if (is_array ($b)) {
            return strnatcasecmp (key($a), key($b));
        } else {
            return -1;
        }
    } else {
        if (is_array ($b)) {
            return 1;
        } else {
            return strnatcasecmp ($a, $b);
        }
    }
}

示例输出

Array
(
    [0] => Array
        (
            [ADocs] => Array
                (
                )

        )

    [1] => Array
        (
            [Special Docs] => Array
                (
                    [0] => doc4.txt
                    [1] => doc3.txt
                )

        )

    [2] => doc5.txt
    [3] => test.txt
    [4] => test1.txt
    [5] => test2.txt
    [6] => test3.txt
)

多级排序(无限制)

function cmp (&$a,&$b) {
    if (is_array($a)){
        usort($a[key($a)], 'cmp');
        if (is_array ($b)) {
            return strnatcasecmp (key($a), key($b));
        } else {
            return -1;
        }
    } else {
        if (is_array ($b)) {
            return 1;
        } else {
            return strnatcasecmp ($a, $b);
        }
    }
}

usort ($dir, 'cmp');

示例输出

Array
(
    [0] => Array
        (
            [ADocs] => Array
                (
                )

        )

    [1] => Array
        (
            [Special Docs] => Array
                (
                    [0] => doc3.txt
                    [1] => doc4.txt
                )

        )

    [2] => doc5.txt
    [3] => test.txt
    [4] => test1.txt
    [5] => test2.txt
    [6] => test3.txt
)