Reputation:
I have this array:
$pets = array(
'cat' => 'Lushy',
'dog' => 'Fido',
'fish' => 'Goldie'
);
If I need to reorder the arrays by having:
fish
dog
cat
in that order and assuming that any of those values may or may not be present, is there a better way than:
$new_ordered_pets = array();
if(isset($pets['fish'])) {
$new_ordered_pets['fish'] = $pets['fish'];
}
if(isset($pets['dog'])) {
$new_ordered_pets['dog'] = $pets['dog'];
}
if(isset($pets['cat'])) {
$new_ordered_pets['cat'] = $pets['cat'];
}
var_dump($new_ordered_pets);
outputs:
Array
(
[fish] => Goldie
[dog] => Fido
[cat] => Lushy
)
Is there a cleaner way, perhaps some inbuilt function I'm not aware of that you simply supply the array to be reordered and the indexes you would like it to be recorded by and it does the magic?
Upvotes: 1
Views: 95
Reputation: 197682
You already have the order, so you only need to assign values (Demo):
$sorted = array_merge(array_flip($order), $pets);
print_r($sorted);
Output:
Array
(
[fish] => Goldie
[dog] => Fido
[cat] => Lushy
)
Related: Sort an array based on another array?
Upvotes: 2
Reputation: 227230
You can use uksort
to sort your array (by keys) based on another array (this will work in PHP 5.3+ only):
$pets = array(
'cat' => 'Lushy',
'dog' => 'Fido',
'fish' => 'Goldie'
);
$sort = array(
'fish',
'dog',
'cat'
);
uksort($pets, function($a, $b) use($sort){
$a = array_search($a, $sort);
$b = array_search($b, $sort);
return $a - $b;
});
DEMO: http://codepad.viper-7.com/DCDjik
Upvotes: 3