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' );
outis
  • 75,655
  • 22
  • 151
  • 221
Jesse
  • 479
  • 7
  • 22

3 Answers3

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.

Matthew
  • 47,584
  • 11
  • 86
  • 98
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.

Community
  • 1
  • 1
Austin M
  • 594
  • 1
  • 4
  • 19
  • Thanks, I've tried all functions in that topic before but it didn't work because my arrays weren't the same size – Jesse Feb 22 '11 at 20:40
0
array_merge(array_combine($sort_array, array_fill(0, count($sort_array), null))
   , $array_that_needs_sorting);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405