0

I have this array. how can i sort it according to desc or asc with respect to id.

Array
(
    [0] => Array
        (
            [data] => Array
                (
                    [id] => 1
                    [title] => Ferrari
                    [price] => 15
                    [model] => 1997
                    [color] => Green
                    [speed] => 80
                )

        )

    [1] => Array
        (
            [data] => Array
                (
                    [id] => 3
                    [title] => Audi
                    [price] => 255
                    [model] => 55
                    [color] => Green
                    [speed] => 99
                )

        )

    [2] => Array
        (
            [data] => Array
                (
                    [id] => 4
                    [title] => BMW
                    [price] => 55
                    [model] => 444
                    [color] => Blue
                    [speed] => 123
                )

        )

)

Thanks.

3
  • What is the result that you'd like to obtain? Have you made any attempts so far? Commented Apr 17, 2014 at 16:37
  • 1
    array_multisort(). "how to sort multi dimensional array". Commented Apr 17, 2014 at 16:37
  • Check stackoverflow.com/questions/7425799/… Commented Apr 17, 2014 at 16:38

2 Answers 2

2

You can use usort:

usort($array, function($a, $b) {
    return $a['data']['id'] < $b['data']['id']? -1 : 1;
});
Sign up to request clarification or add additional context in comments.

Comments

1

I did a quick search on multidimensional array sorting and this came up. It seems like a good solution.

http://www.firsttube.com/read/sorting-a-multi-dimensional-array-with-php/

since you have your sub arrays encapsulated in a "data" array you need to change the 3rd line of the function:

function subval_sort($a,$subkey) {
    foreach($a as $k=>$v) {
        $b[$k] = strtolower($v['data'][$subkey]);
    }
    asort($b);
    foreach($b as $key=>$val) {
        $c[] = $a[$key];
    }
    return $c;
}

$sorted_cars = subval_sort($car_array,'id'); 
print_r($sorted_cars);

I'd start there and see what that returns.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.