如何在PHP中按键对关联多维数组进行排序?

时间:2011-08-18 20:50:59

标签: php sorting multidimensional-array associative-array

我有以下数组:

$data['uploads']['ccc'] = 'something';
$data['uploads']['bbb'] = 'something';
$data['uploads']['aaa'] = 'something';
$data['downloads']['ccc'] = 'something';
$data['downloads']['aaa'] = 'something';
$data['downloads']['bbb'] = 'something';

我需要按键按字母顺序排序,因此最终结果必须是:

$data['downloads']['aaa'] = 'something';
$data['downloads']['bbb'] = 'something';
$data['downloads']['ccc'] = 'something';
$data['uploads']['aaa'] = 'something';
$data['uploads']['bbb'] = 'something';
$data['uploads']['ccc'] = 'something';

尝试各种自定义排序功能,没有运气..有什么想法吗?

2 个答案:

答案 0 :(得分:2)

ksort($data);

http://php.net/manual/en/function.ksort.php

同样来自PHP文档中的注释:

这是一个按键递归排序多维数组的函数:

function deep_ksort(&$arr) { 
    ksort($arr); 
    foreach ($arr as &$a) { 
        if (is_array($a) && !empty($a)) { 
            deep_ksort($a); 
        } 
    } 
} 

答案 1 :(得分:1)

您可以使用array_multisort http://www.php.net/manual/en/function.array-multisort.php

<?php
   $ar = array(
   array("10", 11, 100, 100, "a"),
   array(   1,  2, "2",   3,   1)
  );
  array_multisort($ar[0], SORT_ASC, SORT_STRING,
            $ar[1], SORT_NUMERIC, SORT_DESC);
  var_dump($ar);
 ?>