我希望按照sql ORDER BY VALUES()
中的特定值对数据集合进行排序,但是在PHP中。我有像这样的数组
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
我希望按类型但不按字母顺序排列订单数据,而是按照我指定的特定值排序,按类型other
排序,然后按drink
排序,然后按fruit
排序。所以结果应该是:
$array = array(
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
);
我尝试了usort
,但我不知道如何与2个值进行比较来实现这一目标。感谢。
答案 0 :(得分:2)
您也可以尝试这种方式,
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
// array_flip turns 0 => 'other', 1 => 'drink', ... into 'other' => 0, 'drink' => 1, ...
$order=array_flip(array('other','drink','fruit'));
usort($array, function($x, $y) use($order) {
if (!isset($order[$x['type']], $order[$y['type']])) {
// none of the ids have order, so sort by bare type
return $x['type'] - $y['type'];
}
else if (!isset($order[$x['type']])) {
// x does not have order, put it last
return 1;
}
else if (!isset($order[$y['type']])) {
// y does not have order, put it last
return -1;
}
// both have types, use them
return $order[$x['type']] - $order[$y['type']];
});
echo "<pre>";
print_r($array);
输出: - 阵列
(
[0] => Array
(
[name] => Computer
[type] => other
)
[1] => Array
(
[name] => Water
[type] => other
)
[2] => Array
(
[name] => Milk
[type] => drink
)
[3] => Array
(
[name] => Coffee
[type] => drink
)
[4] => Array
(
[name] => Orange
[type] => fruit
)
)
答案 1 :(得分:1)
是的,您可以使用usort
之类的:
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
usort($array,function($a,$b){
//Define the order
$order = array( 'other' => 0 , 'drink' => 1, 'fruit' => 2 );
//Compare the order
return $order[ $a[ 'type' ] ] > $order[ $b[ 'type' ] ];
});
echo "<pre>";
print_r( $array );
echo "</pre>";
这将导致:
Array
(
[0] => Array
(
[name] => Computer
[type] => other
)
[1] => Array
(
[name] => Water
[type] => other
)
[2] => Array
(
[name] => Milk
[type] => drink
)
[3] => Array
(
[name] => Coffee
[type] => drink
)
[4] => Array
(
[name] => Orange
[type] => fruit
)
)
如果数组中有一些类型,你可以这样做以确保将undefined放在最后一个。
usort($array,function($a,$b){
$order = array( 'other' => 0 , 'drink' => 1, 'fruit' => 2 );
$aOrder = isset( $order[ $a[ 'type' ] ] ) ? $order[ $a[ 'type' ] ] : 1000000000000;
$bOrder = isset( $order[ $b[ 'type' ] ] ) ? $order[ $b[ 'type' ] ] : 1000000000000;
return $aOrder > $bOrder;
});