PHP是否能够按照另一个数组(B)定义的顺序对项目数组(A)进行排序?例如。 B中首先出现的项目决定在排序A时应该首先出现哪个项目。
$order_to_sort_by = array("Gold", "Silver", "Bronze");
$items_to_sort = array("Bronze", "Silver", "Bronze", "Gold", "Bronze", "Silver");
some_sort_function($items_to_sort, $order_to_sort_by);
结果:
Gold
Silver
Silver
Bronze
Bronze
Bronze
编辑:建议的副本似乎使用另一个数组的键来确定数组中的哪些键应该用于排序。有点不清楚,但我认为这不重复。
答案 0 :(得分:2)
你可以试试这样的事情
$order_to_sort_by = array("Gold", "Silver", "Bronze");
$items_to_sort = array("Bronze", "Silver", "Bronze", "Gold", "Bronze", "Silver");
$order_to_sort_by_reversed = array_flip($order_to_sort_by);
$sortByArray = function($a, $b) use ($order_to_sort_by_reversed)
{
return $order_to_sort_by_reversed[$a] - $order_to_sort_by_reversed[$b];
};
usort($items_to_sort, $sortByArray);
var_dump($items_to_sort);
答案 1 :(得分:1)
您可以使用usort
函数来定义如何比较数组元素。例如:
$order_to_sort_by = array("Gold", "Silver", "Bronze");
$items_to_sort = array("Bronze", "Silver", "Bronze", "Gold", "Bronze", "Silver");
usort(
// What to sort. Input array will be changed!
$items_to_sort,
// Lets define comparing function inplace
// ...just cause we can use anonymous functions:
function($a, $b) use ($order_to_sort_by) {
// Find position of two comparing elements
// ...in our ranking array to find what element
// ...is 'greater' than another
$a_pos = array_search($a, $order_to_sort_by);
$b_pos = array_search($b, $order_to_sort_by);
// 0 means that items will not be swapped
// 1 for moving $b up
// -1 for moving $b down
if ($a_pos == $b_pos) {
return 0;
} else if ($a_pos > $b_pos) {
return 1;
} else {
return -1;
}
// I hope in php7 it would be able
// to use `spaceship` operator in this case
// instead of these if`s:
// return $a <=> $b
}
);
var_dump($items_to_sort);