我有2个阵列。 1个阵列,带有用户的角色。还有一个具有特定顺序的所有角色的数组。
$roles = Array
(
[0] => Array
(
[id] => 22465
[name] => Rank 1
[position] => 24
[color] => 16711680
)
[1] => Array
(
[id] => 59454
[name] => Rank 2
[position] => 15
[color] => 15844367
)
[2] => Array
(
[id] => 62280
[name] => Rank 3
[position] => 2
[color] => 65494
)
[3] => Array
(
[id] => 67139
[name] => Rank 4
[position] => 10
[color] => 1146986
)
[4] => Array
(
[id] => 75372
[name] => Rank 5
[position] => 25
[color] => 1146986
)
[5] => Array
(
[id] => 75373
[name] => Rank 6
[position] => 18
[color] => 1146986
)
...
)
我有用户角色数组:
$userdata = Array
(
[roles] => Array
(
[0] => 22465
[1] => 59454
[2] => 62280
[3] => 67139
[4] => 75372
[5] => 75373
)
[data] => Array
(
[0] => 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 (size=2)
'roles' =>
array (size=6)
0 => int 75372
1 => int 22465
2 => int 75373
3 => int 59454
4 => int 67139
5 => int 62280
'data' =>
array (size=1)
0 => string 'irrelevant' (length=10)
与@tangientlylyperpenticular用途相同的代码
array_column()
创建查找数组和箭头函数语法,以避免必须编写
use()
和return
。 demo
$map = array_column($roles, 'position', 'id');
usort($userdata['roles'], fn($a, $b) => $map[$b] <=> $map[$a]);
var_export($userdata);