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

时间:2014-07-29 14:10:47

标签: 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',
    ],
]

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

e.g:

$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',
    ],
]

我应该使用什么?

1 个答案:

答案 0 :(得分:5)

只需使用usort()

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

检查fiddle

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

$sortLikeThis = array_flip($sortLikeThis);

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

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

相关问题