这里是一个非常幼稚的,直接的方式做你想做的
<?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
)
)
[你有什么试过吗?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)参见[关于堆栈溢出](http:// stackoverflow。 COM /约)。 –
嗯,首先想到的是,你可以使用'usort'和一个匿名回调函数来检查$ a和$ b在你的顺序数组中的位置,并使用它来确定它是否应该返回1,0或-1。 – crush
我会遍历第一个数组,爆炸空间字符上的每个项目,并从第二个数组中的爆炸字符串搜索姓氏。然后,我将使用搜索中找到的位置构建一个结果数组作为索引来插入全名。要这样做,你需要'explode'和'array_search',再加上'foreach'进行循环。 – halfer