I have the following array:
$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
]
];
And I want to sort it so it looks like this:
$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
]
];
So basically I need to order by product_id
and user_id
in such a way that it selects the lower number product_id
from each user before proceeding to the next.
I tried to use usort
but I couldn't get it to work.
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;
}
});
I also tried array_multisort
but all I could get it to do is to order using the same order that I already retrieve from the database.
The sort() callback function usually receives two arguments, say a and b, which are nothing but two elements of the array on which sort() was called and the callback function runs for each possible pair of elements of the array.
To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.
Assumption is your values is integers:
usort($campaigns, function($a, $b){
if($a['product_id'] == $b['product_id']){
return $a['user_id'] - $b['user_id'];
} else {
return $a['product_id'] - $b['product_id'];
}
});
Also you can use database ordering with ORDER BY product_id, user_id
clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With