Php usort数组由两个值组成
我有以下数组Php usort数组由两个值组成,php,arrays,sorting,Php,Arrays,Sorting,我有以下数组 $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'=>
$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\u type
对其进行排序。顺序应该是event\u 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");
例如,看看事件类型
是如何排序的。它按以下顺序对ID
进行排序8、0、6
。我需要它是0,6,8
。对于摄像机
也一样。订购后,ID顺序为2,7,4
,我需要它2,4,7
对如何解决这个问题有什么建议吗?我是否正确地使用了usort?您应该始终比较回调方法中的两个方面。当你在一个元素上达到某个值时,你基本上是在说“这更大”:
if($b['post_type'] == 'event_type') {
return 1;
}
如果两者都是事件类型
?你忽视了这一点
你应该这样做:
function cmp($a, $b)
{
$types = array (
'event_type' => 1,
'post' => 2,
'cameras' => 3
);
$compare1 = $types[$a["post_type"]] - $types[$b["post_type"]];
if ($compare1 === 0){
//same category, compare by id.
return $a["ID"] - $b["ID"];
}else{
//different category, save to ignore the id.
return $compare1;
}
}
注:如果它应该是
$a-$b
或$b-$a
,那就玩玩吧-我总是搞砸了。所以在比较函数中添加ID
。
function cmp($a, $b)
{
$types = array (
'event_type' => 1,
'post' => 2,
'cameras' => 3
);
$compare1 = $types[$a["post_type"]] - $types[$b["post_type"]];
if ($compare1 === 0){
//same category, compare by id.
return $a["ID"] - $b["ID"];
}else{
//different category, save to ignore the id.
return $compare1;
}
}