PHP:有没有更好的方法来对数组的值进行重新排序


PHP: Is there a better way to reorder values of an array?

我有这个数组:

$pets = array(
   'cat' => 'Lushy',
   'dog' => 'Fido',
   'fish' => 'Goldie' 
);

如果我需要通过以下方式对数组进行重新排序:

fish
dog
cat

按照这个顺序,假设这些值中的任何一个可能存在,也可能不存在,是否有比以下更好的方法:

$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);

输出:

Array
(
    [fish] => Goldie
    [dog] => Fido
    [cat] => Lushy
)

有没有一种更干净的方法,也许是一些我不知道的内置函数,您只需提供要重新排序的数组以及您希望记录它的索引,它就会产生魔力?

您可以使用uksort根据另一个数组对数组进行排序(按键)(这仅适用于PHP 5.3+):

$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;
});

演示:http://codepad.viper-7.com/DCDjik

您已经有了订单,因此您只需要分配值(演示):

$sorted = array_merge(array_flip($order), $pets);
print_r($sorted);

输出:

Array
(
    [fish] => Goldie
    [dog] => Fido
    [cat] => Lushy
)

相关:根据另一个数组对数组进行排序?

你需要的是uksort。

// callback 
function pets_sort($a,$b) {
    // compare input vars and return less than, equal to , or greater than 0. 
} 
uksort($pets, "pets_sort");