这是一种非常天真、直接的方法来做你想做的事
<?php
$array = array(
array("full_name" => "Jack"),
array("full_name" => "Bob"),
array("full_name" => "Graham Smith"),
array("full_name" => "Gerry Jones"),
array("full_name" => "Frank Brown")
);
$order = array(
"Jones",
"Brown",
"Smith"
);
function findOrderPosition($term) {
global $order;
for ($i = 0; $i < sizeof($order); $i++) {
if ($term == $order[$i])
return $i;
}
return -1;
}
usort($array, function($a, $b) {
//Get the last names here (checking only the last space delimited token).
$arra = explode(' ', $a['full_name']);
$arrb = explode(' ', $b['full_name']);
//Find the position in the $order array.
$posa = findOrderPosition($arra[sizeof($arra) - 1]);
$posb = findOrderPosition($arrb[sizeof($arrb) - 1]);
if ($posa == -1) {
return 1; //Couldn't find item $a in the order array, so we want to move $b ahead of it.
}
if ($posb == -1) {
return -1; //Couldn't find item $b in the order array, so we want to move it to the bottom of the array.
}
if ($posa == $posb) {
return 0; //Don't move the item up or down if they are equal.
}
return $posa > $posb ? 1 : -1; //If position of $a is greater than $b then we want to move $a up, otherwise, move it down.
});
print_r($array);
输出:
Array
(
[0] => Array
(
[full_name] => Gerry Jones
)
[1] => Array
(
[full_name] => Frank Brown
)
[2] => Array
(
[full_name] => Graham Smith
)
[3] => Array
(
[full_name] => Jack
)
[4] => Array
(
[full_name] => Bob
)
)