基于2D数组中的相关数据的阵列

问题描述 投票:0回答:2

因此,我已经搜索了几个小时,但是似乎没有线程使我进入了一个工作解决方案。 我的问题;

我有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
php arrays sorting multidimensional-array custom-sort
2个回答
1
投票

                
与@tangientlylyperpenticular用途相同的代码

array_column()

创建查找数组和箭头函数语法,以避免必须编写
use()

return
。 demo

0
投票

$map = array_column($roles, 'position', 'id'); usort($userdata['roles'], fn($a, $b) => $map[$b] <=> $map[$a]); var_export($userdata);

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.