2010-11-13 116 views
0

我有2個數組:顏色和最喜歡的顏色。
我想輸出一個包含所有顏色但最喜歡的顏色排列在頂部的數組,保持相同的排序順序。PHP數組函數,差異和合並

我的例子工作正常,但想知道這是否是正確(最快)的方式來做到這一點。
謝謝

$colors_arr = array("yellow","orange","red","green","blue","purple"); 
print "<pre>Colors: "; 
print_r($colors_arr); 
print "</pre>"; 

$favorite_colors_arr = array("green","blue"); 
print "<pre>Favorite Colors: "; 
print_r($favorite_colors_arr); 
print "</pre>"; 

$normal_colors_arr = array_diff($colors_arr, $favorite_colors_arr); 
print "<pre>Colors which are not favorites: "; 
print_r($normal_colors_arr); 
print "</pre>"; 

// $sorted_colors_arr = $favorite_colors_arr + $normal_colors_arr; 
$sorted_colors_arr = array_merge($favorite_colors_arr, $normal_colors_arr); 
print "<pre>All Colors with favorites first: "; 
print_r($sorted_colors_arr); 
print "</pre>"; 

輸出:

Colors: Array 
(
    [0] => yellow 
    [1] => orange 
    [2] => red 
    [3] => green 
    [4] => blue 
    [5] => purple 
) 

Favorite Colors: Array 
(
    [0] => green 
    [1] => blue 
) 

Colors which are not favorites: Array 
(
    [0] => yellow 
    [1] => orange 
    [2] => red 
    [5] => purple 
) 

All Colors with favorites first: Array 
(
    [0] => green 
    [1] => blue 
    [2] => yellow 
    [3] => orange 
    [4] => red 
    [5] => purple 
) 

回答

0

你可能縮短到

$sorted_colors_arr = array_unique(array_merge($favorite_colors_arr, $colors_arr);