2012-06-27 34 views
1

我有這樣的陣列:PHP:有沒有更好的方法來重新排列數組的值?

$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

的http:// php.net/ksort - 如果這不是您正在尋找的功能,請向下滾動查看相關功能的列表或者在左側查看* all *數組函數。 – hakre

+0

嗯嗨closvoter,如何是一個通用的問題陣列排序_too localized_?如果你想關閉它,搜索並找到一個重複的,因爲可能有一個。但不要以虛假的理由作弊。 –

+0

@邁克爾:聞起來像是一個愚蠢的我會說。因此太局部化了,這個問題已經被問及已經解決了,它太侷限了,不能再問這個問題。 – hakre

回答

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?

+0

+1,這是一個聰明的解決方案:-) –

+0

我遲緩了。 – hakre

+0

'array_merge'的另一個+1 :-) –

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

+0

爲什麼'ksort'不夠? –

+0

@ExplosionPills:'ksort'怎麼知道把它們放在什麼位置? –

+1

我以爲'ksort'會按字母順序排列字符串(或者在這種情況下是'krsort'),但也許它不會。這就是我要問的。我沒有真正檢查過我自己。 –

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"); 
相關問題