如何根据多维数组的项数组键和值对多维数组进行排序?

时间:2010-06-26 14:17:20

标签: php arrays sorting multidimensional-array

我有一系列权限:

array(
  array( "controller" => "somewhere", "action" => "",      "namespace" => "admin", "method" => "GET" ), 
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "" ),
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "GET" )
)

我需要排序,以便首先列出最“具体”的一个。天气与否具体取决于天气与当前加载的控制器,动作和命名空间的相关性。

首先:三个阵列的控制器覆盖相同的区域,但他们的行为却没有。因此,具有特定操作的那些应该排在那些没有的那些之上。

其次:它们共享相同的命名空间,但不是相同的方法。所以具有特定方法的那些应该排在那些没有的那些之后。

如果您有任何想法或有任何需要解释的问题,请问我。我真的很感激能够对这个数组进行排序,所以我不必重做我的架构以获得权限。

// Emil

1 个答案:

答案 0 :(得分:0)

首先定义这两个函数:

function specific_sort($a, $b) {
    $r = more_specific($a, $b, 'controller');
    if ($r == 0) {
        $r = more_specific($a, $b, 'action');
        if ($r == 0) {
            $r = more_specific($a, $b, 'method');
        }
    }
    return $r;
}

function more_specific($a, $b, $key) {
    if (empty($a[$key])) {
        return 1;
    }
    if (empty($b[$key])) {
        return -1;
    }
    return 0;
}

然后:

$rt = array(
  array( "controller" => "somewhere", "action" => "",      "namespace" => "admin", "method" => "GET" ),
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "" ),
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "GET" )
);
usort($rt, 'specific_sort');
print '<pre>';
print_r($rt);
print '</pre>';

应打印出来:

Array
(
    [0] => Array
        (
            [controller] => somewhere
            [action] => index
            [namespace] => admin
            [method] => GET
        )

    [1] => Array
        (
            [controller] => somewhere
            [action] => index
            [namespace] => admin
            [method] => 
        )

    [2] => Array
        (
            [controller] => somewhere
            [action] => 
            [namespace] => admin
            [method] => GET
        )

)