2

I need to sort an array by its keys based on the order of the values in another array. Simple example:

$sort_array = array( 'key1', 'key2' );

$array_that_needs_sorting = array( 'key2' => 'value2', 'key1' => 'value1' );

After sorting, the array should be:

array( 'key1' => 'value1', 'key2' => 'value2' );

3 Answers 3

3

If you know the $sort_array keys are all present in the array that needs to be sorted, you can do this:

$sorted = array_merge(array_flip($keys), $unsorted);

where $keys is $sort_array and $unsorted is $array_that_needs_sorting.

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

Comments

0

You might take a look at Sort an Array by keys based on another Array?. It should give you an idea on how to accomplish that.

1 Comment

Thanks, I've tried all functions in that topic before but it didn't work because my arrays weren't the same size
0
array_merge(array_combine($sort_array, array_fill(0, count($sort_array), null))
   , $array_that_needs_sorting);

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.