PHP高级多维数组排序

时间:2015-02-27 15:51:55

标签: php sorting multidimensional-array

我递归地读取了一个文件夹,我得到了一个像这样的多维数组:

Array
(
   [folder1] => Array
       (
           [sub-folder1] => Array
               (
                   [0] => sub-folder-1-file1.xx
                   [1] => sub-folder-1-file2.xx
                   [2] => sub-folder-1-file3.xx
               )

            [0] => folder-1-file1.xx
            [1] => folder-1-file2.xx
            [2] => folder-1-file3.xx
            [3] => folder-1-file4.xx
            [sub-folder2] => Array
                (
                   [0] => sub-folder-2-file1.xx
                   [1] => sub-folder-2-file1.xx
                )
  ...

我想将其排序为

(
   [folder1] => Array
       (
            [0] => folder-1-file1.xx
            [1] => folder-1-file2.xx
            [2] => folder-1-file3.xx
            [3] => folder-1-file4.xx
            [sub-folder1] => Array
               (
                   [0] => sub-folder-1-file1.xx
                   [1] => sub-folder-1-file2.xx
                   [2] => sub-folder-1-file3.xx
               )
            [sub-folder2] => Array
                (
                   [0] => sub-folder-2-file1.xx
                   [1] => sub-folder-2-file1.xx
                )

就像我们按类型列出而不是简单地按名称列出。

我想我必须使用usort但我无法正确理解它: 我的工作在这里:

usort($array, function($a, $b){
    if ( (is_array($a) && is_array($b)) || (!is_array($a) && !is_array($b)) )
       return 0;
    if ( is_array($a) )
       return -1;
    return 1;
});

任何帮助将不胜感激。感谢。

我解决了这个问题:

 foreach ($array as $key => $value)
 {
    ksort($array[$key], SORT_STRING);
 }

1 个答案:

答案 0 :(得分:1)

您可以使用ksort()函数并将所需的排序类型作为第二个参数传递。

假设您的数组名称为$test,那么您需要这样的内容:

ksort($test['folder1'], SORT_STRING); //SORT_STRING compares items as strings

如果你做了

echo '<pre>',print_r($test,1),'</pre>';

你将能够看到你想要的结果。