我正在关注此帖子How can I sort arrays and data in PHP?
我想基于另一个单维数组
对二维数组进行排序数组我要排序
$main = array(array('name' => 'terry', 'age' => '25', 'sex' => 'm', 'status' => 'active'),
array('name' => 'raul', 'age' => '26', 'sex' => 'm', 'status' => 'active'),
array('name' => 'mata', 'age' => '27', 'sex' => 'm', 'status' => 'active'),
array('name' => 'ronaldo', 'age' => '28', 'sex' => 'm', 'status' => 'active'),
array('name' => 'drogba', 'age' => '29', 'sex' => 'm', 'status' => 'active'),
array('name' => 'messi', 'age' => '30', 'sex' => 'm', 'status' => 'active'));
订单数组
$order = array('30','25');
function cmp(array $a, array $b) {
global $order;
return array_search($a['age'], $order) - array_search($b['age'], $order);
}
usort($main, 'cmp');
这是我正在尝试的功能。但它没有对数组进行排序。
所需的输出:我想得到年龄值为30&的数组。 25作为输入二维数组中的前两个数组
我可以使用此代码
function cmp(array $a, array $b) {
global $order;
foreach ($order as $ord) {
if (in_array($ord, $a)) {
return true;
}
}
}
但我想避免使用foreach循环
答案 0 :(得分:1)
试试这个:
$inArray = array(30, 25);
uasort($main, function($a, $b) use ($inArray){
$aAge = $a['age'];
$bAge = $b['age'];
$aWeight = 0;
$bWeight = 0;
if (in_array($aAge, $inArray))
$aWeight++;
if (in_array($bAge, $inArray))
$bWeight++;
if ($aWeight != $bWeight) {
return $aWeight > $bWeight ? -1 : 1;
} else if ($aWeight > 0) {
// need to sort by order which specified in array
$aIndex = array_search($aAge, $inArray);
$bIndex = array_search($bAge, $inArray);
return ($aIndex == $bIndex ? 0 : ($aIndex > $bIndex ? 1 : -1));
} else {
// just compare age values
return ($aAge == $bAge ? 0 : ($aAge > $bAge ? 1 : -1));
}
});