Tomi Seus
Tomi Seus

Reputation: 1161

How to sort an array based on input array?

I'm having trouble sorting an array according to another array. I've tried usort, uksort and uasort but I'm getting nowhere. Other questions on stackoverflow are not directly applicable here, as my array structure is different. I want to sort this multidimensional array:

$main = Array (
    [Technology] => Array ()
    [World] => Array ()
    [Europe] => Array () 
)

By using this index-array:

$index = Array (
    [0] => Europe
    [1] => Technology
    [2] => World
)

Basically, in this example I would want Europe to come first in the $main array, Technology second and World third, as this is their positioning in the $index array. How do I do that? (Please disregard little syntax errors in the arrays above)

Upvotes: 0

Views: 1133

Answers (3)

Jeroen
Jeroen

Reputation: 13257

$main_sort = array()    
foreach ($index as $key => $value) {
    if ($main [$value]) $main_sorted [$value] = $main [$value];
}

Simply loop through the $index array and map those values to a new array using the values from the $main array.

Upvotes: 1

Walter Tross
Walter Tross

Reputation: 12624

This solution works if you don't have any value in $index which is not a key in $main (as is the case in your example):

$sorted = array_merge(array_flip($index), $main);

If the values of $index are a superset of the keys of $main, a possible solution is:

$sorted = array_intersect_assoc(array_merge(array_flip($index), $main), $main);

Keep in mind that letting PHP functions work on arrays is much faster than doing so "explicitly"

Upvotes: 0

Maciej Łebkowski
Maciej Łebkowski

Reputation: 3887

Given $index and $main,

uksort($main, function ($k, $k2) use ($index) {
  return array_search($k, $index) - array_search($k2, $index);
});

Array will be sorted according to keys specified in $index. Behavior of not-matched keys is unspecified.

Upvotes: 0

Related Questions