我很惭愧地问这个问题,所以我会快点。
我有一个看起来像这样的数组:
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);
感谢。
答案 0 :(得分: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
)
答案 1 :(得分: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;
};