2

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?

Isis
  • 4,608
  • 12
  • 39
  • 61
  • Related, but not duplicate since this is a multidimensional array: http://stackoverflow.com/questions/348410/sort-an-array-based-on-another-array – nickb Jul 29 '14 at 14:15

1 Answers1

5

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.

Alma Do
  • 37,009
  • 9
  • 76
  • 105