开发者

PHP array functions, difference and merge

I have 2 arrays: colors and favorite colors.

I want to output an array with all the colors but the favorite colors on top, keeping the same sort order.

My example is working fine, but wanted to know if this is the correct (fastest) way to do this.

Thank you

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

output:

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
)


You could possibly shorten it to

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜