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.

Ali Nouman
  • 3,304
  • 9
  • 32
  • 53

2 Answers2

2

You can use usort:

usort($array, function($a, $b) {
    return $a['data']['id'] < $b['data']['id']? -1 : 1;
});
hindmost
  • 7,125
  • 3
  • 27
  • 39
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.

wullaski
  • 89
  • 4