开发者

How do I sort a multidimensional array depending on it's items array keys and values?

开发者 https://www.devze.com 2023-01-04 16:32 出处:网络
I have an array of permissions: array( array( \"controller\" => \"somewhere\", \"action\" => \"\",\"namesp开发者_如何转开发ace\" => \"admin\", \"method\" => \"GET\" ),

I have an array of permissions:

array(
  array( "controller" => "somewhere", "action" => "",      "namesp开发者_如何转开发ace" => "admin", "method" => "GET" ), 
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "" ),
  array( "controller" => "somewhere", "action" => "index", "namespace" => "admin", "method" => "GET" )
)

That I need to sort, so that the most "specific" one is listed first. Weather or not it's specific is determined by its relevance to the currently loaded controller, action and namespace.

Firstly: The three arrays' controllers cover the same area, but their actions doesn't. So the ones with a specific action should be sorted above those without.

Secondly: They share the same namespace, but not the same method. So the ones with a specific method should be sorted above those without.

If you have any ideas, or have any questions that needs explenations, please ask me. I would really appreciate being able to sort this array, so I don't have to redo my architecture for the permissions.

// Emil


First define these two functions:

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;
}

Then:

$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>';

It should print out:

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
        )

)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号