0

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.

1
  • Have you tried writing a usort function to sort it yourself? Commented May 29, 2014 at 13:20

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done. If order_sub_order_sort is one-time use, you can even just use an anonymous function as the second parameter to usort.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.