usort数组我有以下阵列由两个值
$q = array(
array(
'ID'=>'0',
'post_date'=>'2014-09-20 20:01:52',
'post_type'=>'event_type'
),
array(
'ID'=>'1',
'post_date'=>'2014-09-13 11:33:10',
'post_type'=>'post'
),
array(
'ID'=>'2',
'post_date'=>'2014-09-11 16:55:32',
'post_type'=>'cameras'
),
array(
'ID'=>'3',
'post_date'=>'2014-09-10 17:44:52',
'post_type'=>'post'
),
array(
'ID'=>'4',
'post_date'=>'2014-09-09 17:44:52',
'post_type'=>'cameras'
),
array(
'ID'=>'5',
'post_date'=>'2014-09-07 15:20:10',
'post_type'=>'post'
),
array(
'ID'=>'6',
'post_date'=>'2014-07-08 20:01:52',
'post_type'=>'event_type'
),
array(
'ID'=>'7',
'post_date'=>'2014-07-06 15:26:28',
'post_type'=>'cameras'
),
array(
'ID'=>'8',
'post_date'=>'2014-06-30 17:44:52',
'post_type'=>'event_type'
),
);
我需要post_type
在我指定的顺序排序此。顺序应该是event_type
,然后post
然后cameras
。我可以实现这一点,没有问题,用以下代码
function cmp($a, $b)
{
if($b['post_type'] == 'event_type') {
return 1;
}
elseif($a['post_type'] == 'event_type') {
return -1;
}
elseif($b['post_type'] == 'post') {
return 1;
}
elseif($a['post_type'] == 'post') {
return -1;
}
elseif($b['post_type'] == 'cameras') {
return 1;
}
elseif($a['post_type'] == 'cameras') {
return -1;
}
return ($a < $b) ? -1 : 1;
}
usort($q, "cmp");
该阵列由post_type
如I所指明正确排序。我遇到问题的地方在于,这种排序不会使数组按ID
排序。让我解释。下面是整理
array(9) {
[0]=>
array(3) {
["ID"]=>
string(1) "8"
["post_date"]=>
string(19) "2014-06-30 17:44:52"
["post_type"]=>
string(10) "event_type"
}
[1]=>
array(3) {
["ID"]=>
string(1) "0"
["post_date"]=>
string(19) "2014-09-20 20:01:52"
["post_type"]=>
string(10) "event_type"
}
[2]=>
array(3) {
["ID"]=>
string(1) "6"
["post_date"]=>
string(19) "2014-07-08 20:01:52"
["post_type"]=>
string(10) "event_type"
}
[3]=>
array(3) {
["ID"]=>
string(1) "1"
["post_date"]=>
string(19) "2014-09-13 11:33:10"
["post_type"]=>
string(4) "post"
}
[4]=>
array(3) {
["ID"]=>
string(1) "3"
["post_date"]=>
string(19) "2014-09-10 17:44:52"
["post_type"]=>
string(4) "post"
}
[5]=>
array(3) {
["ID"]=>
string(1) "5"
["post_date"]=>
string(19) "2014-09-07 15:20:10"
["post_type"]=>
string(4) "post"
}
[6]=>
array(3) {
["ID"]=>
string(1) "2"
["post_date"]=>
string(19) "2014-09-11 16:55:32"
["post_type"]=>
string(7) "cameras"
}
[7]=>
array(3) {
["ID"]=>
string(1) "7"
["post_date"]=>
string(19) "2014-07-06 15:26:28"
["post_type"]=>
string(7) "cameras"
}
[8]=>
array(3) {
["ID"]=>
string(1) "4"
["post_date"]=>
string(19) "2014-09-09 17:44:52"
["post_type"]=>
string(7) "cameras"
}
}
看,例如,event_type
的排序后的输出。它按以下顺序排列ID
8, 0, 6
。我需要它是0, 6, 8
。 cameras
也一样。订购后,身份证订单为2, 7, 4
,因为我需要它2, 4, 7
有关如何解决此问题的任何建议?我正确使用usort
吗?
因此,添加'ID'到你的比较函数。 – 2014-10-07 19:06:27