Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sorting array of arrays using two conditions

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.

like image 942
Wern Ancheta Avatar asked Apr 12 '16 06:04

Wern Ancheta


People also ask

How do you sort an array with two conditions?

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.

How do you sort a custom 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.


1 Answers

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.

like image 81
vp_arth Avatar answered Sep 19 '22 20:09

vp_arth