1

我不好意思问这个问题,所以我会尽快回答。

我有一个看起来像这样的数组:

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)

我想对其进行排序以使其看起来像:

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

我没有排序规则,我只有输出模型数组。

我试过了,但我不知道在闭包内写什么:

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

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

 usort($list, $myCustomFilter);

谢谢。

4

2 回答 2

3

它不需要是一个排序:

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

输出:

Array
(
    [0] => index
    [1] => update
    [2] => renew
    [3] => create
    [4] => restore
    [5] => check
    [6] => transfer
    [7] => delete
)
于 2013-08-12T09:01:27.357 回答
0

以下应该做你需要的。它按 中的位置排序$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;
};
于 2013-08-12T09:01:36.133 回答