2010-11-13 80 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);