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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.