arbme
arbme

Reputation: 4931

Sort array using two values

I am trying to sort an array using two values (order, sub_order) so that they are orders like 1.1, 1.2, 2.1, 2.1.

Below is an example of the array as it is now and the second is the array sorted correctly by the order and sub_order values.

Array
(
    [0] => Array
        (
            [id] => 1
            [order] => 1
            [sub_order] => 2
            [title] => Blah 
        )

    [1] => Array
        (
            [id] => 3
            [order] => 2
            [sub_order] => 2
            [title] => Blah 
        )

    [2] => Array
        (
            [id] => 2
            [order] => 1
            [sub_order] => 1
            [title] => Blah 
        )

    [3] => Array
        (
            [id] => 4
            [order] => 2
            [sub_order] => 1
            [title] => Blah 
        )

)

Ordered correctly...

Array
(
    [0] => Array
        (
            [id] => 2
            [order] => 1
            [sub_order] => 1
            [title] => Blah 
        )

    [1] => Array
        (
            [id] => 1
            [order] => 1
            [sub_order] => 2
            [title] => Blah 
        )

    [2] => Array
        (
            [id] => 4
            [order] => 2
            [sub_order] => 1
            [title] => Blah 
        )

    [3] => Array
        (
            [id] => 3
            [order] => 2
            [sub_order] => 2
            [title] => Blah 
        )

)

Any help would be great.

Upvotes: 0

Views: 52

Answers (1)

Halcyon
Halcyon

Reputation: 57709

Use usort

usort($array, "order_sub_order_sort");
function order_sub_order_sort($a, $b) {
    if ($a["order"] != $b["order"]) {
        return $a["order"] - $b["order"];
    }
    return $a["sub_order"] - $b["sub_order"]
}

Change $a-$b for $b-$a if you want to sort the other way around. I always forget which is ascending and which is descending.

Upvotes: 3

Related Questions