Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting array based on inner-array key-value [duplicate]

Tags:

php

I have an array like one mentioned below

Array
(
[6] => Array
    (
        [name] => Extras
        [total_products] => 0
        [total_sales] => 0
        [total_affiliation] => 0
    )

[5] => Array
    (
        [name] => Office Products
        [total_products] => 7
        [total_sales] => 17
        [total_affiliation] => 8
    )

[1] => Array
    (
        [name] => Hardware Parts
        [total_products] => 6
        [total_sales] => 0
        [total_affiliation] => 0
    )

)

Right now, order is: Extras, Office Products, Hardware Parts

I want to sort main array in such as way that it is order by total_sales of inner-array in desc order

so order will be: Office Products, Extras, Hardware Parts

Any help guys

like image 923
I-M-JM Avatar asked Jun 30 '11 06:06

I-M-JM


1 Answers

PHP 5.3:

usort($array, function ($a, $b) { return $b['total_sales'] - $a['total_sales']; });

PHP 5.2-:

usort($array, create_function('$a,$b', 'return $b["total_sales"] - $a["total_sales"];'));
like image 50
deceze Avatar answered Oct 26 '22 04:10

deceze