I have an array as table:
$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',
],
]
I want to get sortered array ($unsorted) by sort key like in $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',
],
]
What should I use?
Just use usort()
:
usort($unsorted, function($x, $y) use ($sortLikeThis)
{
return array_search($x['sort'], $sortLikeThis) - array_search($y['sort'], $sortLikeThis);
});
Check the fiddle.
Hint: with current structure, you'll trigger array_search()
(linear time) for each element, which may be slow. Thus, it can be optimized:
$sortLikeThis = array_flip($sortLikeThis);
usort($unsorted, function($x, $y) use ($sortLikeThis)
{
return $sortLikeThis[$x['sort']] - $sortLikeThis[$y['sort']];
});
With this each lookup will be O(1)
since it's a hash-table search.