PHP按另一个数组(表)按键对数组进行排序

Isi*_*sis 2 php arrays sorting

我有一个数组作为表:

$sortLikeThis = [
    '5',
    '3',
    '7'
    '1',
];

$unsorted = [
    [
        'sort' => '7',
        'name' => 'Test',
    ],
    [
        'sort' => '1',
        'name' => 'Test 2',
    ],
    [
        'sort' => '3',
        'name' => 'Test 3',
    ],
    [
        'sort' => '5',
        'name' => 'Test 4',
    ],
    [
        'sort' => '7',
        'name' => 'Test 4',
    ],
]
Run Code Online (Sandbox Code Playgroud)

我想通过排序键获得分拣数组($ unsorted),如$ sortLikeThis.

例如:

$output = [
    [
        'sort' => '5',
        'name' => 'Test 4',
    ],
    [
        'sort' => '3',
        'name' => 'Test 3',
    ],
    [
        'sort' => '7',
        'name' => 'Test',
    ],
    [
        'sort' => '7',
        'name' => 'Test 4',
    ],
    [
        'sort' => '1',
        'name' => 'Test 2',
    ],
]
Run Code Online (Sandbox Code Playgroud)

我该怎么用?

Alm*_* Do 5

只需使用usort():

usort($unsorted, function($x, $y) use ($sortLikeThis)
{
   return array_search($x['sort'], $sortLikeThis) - array_search($y['sort'], $sortLikeThis);
});
Run Code Online (Sandbox Code Playgroud)

检查小提琴.

提示:对于当前结构,您将为array_search()每个元素触发(线性时间),这可能很慢.因此,它可以优化:

$sortLikeThis = array_flip($sortLikeThis);

usort($unsorted, function($x, $y) use ($sortLikeThis)
{
   return $sortLikeThis[$x['sort']] - $sortLikeThis[$y['sort']];
});
Run Code Online (Sandbox Code Playgroud)

这样每次查找都是O(1)因为它是一个哈希表搜索.