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

时间:2012-06-27 22:03:22

标签: php arrays

我有这个数组:

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

是否有一种更清洁的方式,也许是一些内置函数我不知道你只是提供要重新排序的数组以及你希望它被记录的索引并且它具有魔力?

3 个答案:

答案 0 :(得分:3)

您可以使用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;
});

DEMO:http://codepad.viper-7.com/DCDjik

答案 1 :(得分:2)

您已有订单,因此您只需指定值(Demo):

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

print_r($sorted);

输出:

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

相关:Sort an array based on another array?

答案 2 :(得分:0)

您需要的是uksort

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

uksort($pets, "pets_sort");
相关问题