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 that 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 product_id and user_id so that it selects a smaller number of product_id from each user before moving on to the next.
I tried to use usort , but I could not 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 do was order using the same order that I was already extracting from the database.