views:

36

answers:

1

Hi there.

I have an array of permissions:

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" )
)

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

A: 

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
        )

)
Lukman
Thank you. I came to the same conclusion, but where hoping for something that was already build into the php core (or some plugin).
Ekampp