1

I'm ashamed to ask this question, so i'll make it quick.

I have an array which look like that :

array (size=11)
  0 => string 'create' (length=6)
  1 => string 'index' (length=5)
  2 => string 'restore' (length=7)
  3 => string 'renew' (length=5)
  4 => string 'check' (length=5)
  5 => string 'transfer' (length=8)
  6 => string 'delete' (length=6)
  7 => string 'update' (length=6)

And I want to sort it in order to make it look like :

array (size=...)
  1 => string 'index' (length=5)
  2 => string 'update' (length=6)
  3 => string 'renew' (length=5)
  and all other values no matter which order

I have no rule to sort, I only have the output model array.

I tried but i have no idea what to write inside the closure :

$modelMenu = array('index', 'update', 'renew');

$myCustomFilter = function($a, $b) use ($modelMenu) {
     var_dump($a, $b);
};

 usort($list, $myCustomFilter);

Thanks.

ShameOnMe
  • 13
  • 2

2 Answers2

3

It doesn't need to be a sort:

$list = array(
  0 => 'create'
  ,1 => 'index'
  ,2 => 'restore'
  ,3 => 'renew'
  ,4 => 'check'
  ,5 => 'transfer'
  ,6 => 'delete'
  ,7 => 'update'
);
$modelMenu = array('index', 'update', 'renew');
$list = array_diff($list,$modelMenu); //Filter out elements in $modelMenu from $list
$list = array_merge($modelMenu,$list); //Put the $modelMenu elements back in at the beginning
echo '<pre>'.print_r($list,true).'</pre>';

Output:

Array
(
    [0] => index
    [1] => update
    [2] => renew
    [3] => create
    [4] => restore
    [5] => check
    [6] => transfer
    [7] => delete
)
MDEV
  • 10,240
  • 1
  • 29
  • 49
0

The following should do what you need. It sorts by the position in $modelMenu.

$myCustomFilter = function($a, $b) use ($modelMenu) {
    $aSortOrder = array_search($a, $modelMenu);
    $bSortOrder = array_search($b, $modelMenu);
    if($aSortOrder === false){
        $aSortOrder = count($modelMenu);
    }
    if($bSortOrder === false){
        $bSortOrder = count($modelMenu);
    }
    return $aSortOrder-$bsortOrder;
};
Jim
  • 21,521
  • 5
  • 49
  • 80