因此,我已经搜索了几个小时,但是似乎没有线程使我进入了一个工作解决方案。 我的问题;
我有2个阵列。 1个阵列,带有用户的角色。还有一个具有特定顺序的所有角色的数组。$roles = [
[
'id' => 22465,
'name' => 'Rank 1',
'position' => 24,
'color' => 16711680,
],
[
'id' => 59454,
'name' => 'Rank 2',
'position' => 15,
'color' => 15844367,
],
[
'id' => 62280,
'name' => 'Rank 3',
'position' => 2,
'color' => 65494,
],
[
'id' => 67139,
'name' => 'Rank 4',
'position' => 10,
'color' => 1146986,
],
[
'id' => 75372,
'name' => 'Rank 5',
'position' => 25,
'color' => 1146986,
],
[
'id' => 75373,
'name' => 'Rank 6',
'position' => 18,
'color' => 1146986,
],
];
我有用户角色数组:
$userdata = [
'roles' => [22465, 59454, 62280, 67139, 75372, 75373],
'data' => ['irrelevant']
];
我希望将用户角色数组分类为另一个数组中的角色“位置”。
我认为瓶颈是必须用子阵列[角色] [位置]调用数组才能获得工作的命令。
角色子阵列的结果应为:
[0] => 75372
[1] => 22465
[2] => 75373
[3] => 59454
[4] => 67139
[5] => 62280
// First, build a lookup table relating id directly to position
$ranks = [];
foreach($roles as $role) {
$ranks[$role['id']] = $role['position'];
}
var_dump($ranks);
// Now sort the table using the lookup table we just produced
//
usort($userdata['roles'], function($a, $b) use ($ranks){
return $ranks[$b] <=> $ranks[$a];
});
var_dump($userdata);
userdata
阵列的con
array_column()
创建查找数组和箭头函数语法,以避免必须编写
use()
和return
。 demo$map = array_column($roles, 'position', 'id');
usort($userdata['roles'], fn($a, $b) => $map[$b] <=> $map[$a]);
var_export($userdata);