【发布时间】:2016-08-02 13:33:21
【问题描述】:
我有以下数组:
$arr = [
[
'user_id' => 1,
'product_id' => 1
],
[
'user_id' => 1,
'product_id' => 2
],
[
'user_id' => 1,
'product_id' => 3
],
[
'user_id' => 2,
'product_id' => 1
],
[
'user_id' => 2,
'product_id' => 2
],
[
'user_id' => 3,
'product_id' => 1
]
];
我想对其进行排序,使其看起来像这样:
$arr = [
[
'user_id' => 1,
'product_id' => 1
],
[
'user_id' => 2,
'product_id' => 1
],
[
'user_id' => 3,
'product_id' => 1
],
[
'user_id' => 1,
'product_id' => 2
],
[
'user_id' => 2,
'product_id' => 2
],
[
'user_id' => 1,
'product_id' => 3
]
];
所以基本上我需要按product_id 和user_id 订购,以便在继续下一个用户之前从每个用户中选择较低的数字product_id。
我尝试使用usort,但无法使用。
usort($campaigns, function($a, $b){
if($a['product_id'] == $b['product_id']){
return 0;
}
if($a['product_id'] < $b['product_id']){
if($a['user_id'] == $b['user_id']){
return 1;
}
if($a['user_id'] < $a['user_id']){
return 0;
}
return -1;
}else{
if($a['user_id'] == $a['user_id']){
return -1;
}
if($a['user_id'] < $a['user_id']){
return 0;
}
return 1;
}
});
我也尝试了array_multisort,但我所能做的就是使用我已经从数据库中检索到的相同订单进行订购。
【问题讨论】:
-
您的
usort代码不正确;您应该通过第一个字段与</>进行比较,并且仅当第一个字段等于时才比较第二个字段。 -
您是说您正在从数据库中检索,为什么您不直接对查询进行排序?
标签: php sorting multidimensional-array