Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double sorting an array in PHP

Tags:

php

sorting

I need to sort an array in PHP and then sort by its second index if the first index is the same. Let me explain :

The elements would be randomly arranged :

(2,1),(4,4),(2,9),(4,8),(2,35),(2,1),(2,35),(4,4),(4,25),(4,4)

I would need to sort them by the first number first. so the result would be :

(2,1),(2,9),(2,1),(2,35),(4,4),(4,8),(4,4),(4,25),(4,4)

Now you can see all the elements are grouped by the first index together. Now i need to group by the second index "WITHIN" the current grouping. Thus make it look like :

(2,1),(2,1),(2,9),(2,35),(4,4),(4,4),(4,4),(4,8),(4,25)

This was just a simple representation of the array. The actual array is below :

Array
(
    [0] => Array
        (
            [practice_id] => 119
            [practice_location_id] => 173
        )

    [1] => Array
        (
            [practice_id] => 2
            [practice_location_id] => 75
        )

    [2] => Array
        (
            [practice_id] => 18
            [practice_location_id] => 28
        )

    [3] => Array
        (
            [practice_id] => 119
            [practice_location_id] => 174
        )

    [4] => Array
        (
            [practice_id] => 119
            [practice_location_id] => 173
        )

    [5] => Array
        (
            [practice_id] => 2
            [practice_location_id] => 75
        )

    [6] => Array
        (
            [practice_id] => 119
            [practice_location_id] => 174
        )

    [7] => Array
        (
            [practice_id] => 18
            [practice_location_id] => 28
        )

    [8] => Array
        (
            [practice_id] => 18
            [practice_location_id] => 27
        )
)

Would really appreciate some help.

like image 366
YD8877 Avatar asked Dec 29 '22 04:12

YD8877


2 Answers

Use usort with a custom comparison function, which sorts by the first field, but if they are equal, sorts by the second field:

function my_compare($a, $b) {
  if ($a['practice_id'] == $b['practice_id'])
    return $a['practice_location_id'] - $b['practice_location_id'];
  else
    return $a['practice_id'] - $b['practice_id'];
}
like image 77
casablanca Avatar answered Dec 30 '22 16:12

casablanca


function compare_callback($x, $y) {
    if ($x['practice_id'] < $y['practice_id'])
        return 1;
    if ($x['practice_id'] > $y['practice_id'])
        return -1;
    if ($x['practice_id'] == $y['practice_id']) {
        if ($x['practice_location_id'] < $y['practice_location_id'])
            return 1;
        if ($x['practice_location_id'] > $y['practice_location_id'])
            return -1;
        if ($x['practice_location_id'] == $y['practice_location_id'])
            return 0;
    }
}

Use this method with usort()

http://php.net/usort

like image 35
Jonah Avatar answered Dec 30 '22 16:12

Jonah