我有2个阵列:颜色和喜欢的颜色 我想输出一个包含所有颜色但最喜欢的颜色的数组,保持相同的排序顺序。
我的例子工作正常,但想知道这是否是正确(最快)的方法 谢谢
$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 :(得分:0)
您可以将其缩短为
$sorted_colors_arr = array_unique(array_merge($favorite_colors_arr, $colors_arr);