How to Sort an array of associative arrays by value of given key in php


We can sort an array using usort in ascending and descending order,we need to pass function name as parameter in usort. cmp function is very dynamic that sort in ascending and descending order by specified key.

Example - Array Ascending Order

$array = array(
  array('price'=>'1000.50','product'=>'product 1'),
  array('price'=>'8800.50','product'=>'product 2'),
  array('price'=>'200.0','product'=>'product 3')
);

function cmp($a, $b) {
  return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [price] => 134.50
            [product] => product 1
        )

    [1] => Array
        (
            [price] => 2033.0
            [product] => product 3
        )

    [2] => Array
        (
            [price] => 8340.50
            [product] => product 2
        )

)

Example - Array Descending Order

$array = array(
  array('price'=>'1000.50','product'=>'product 1'),
  array('price'=>'8800.50','product'=>'product 2'),
  array('price'=>'200.0','product'=>'product 3')
);

function cmp($a, $b) {
  return $a['price'] < $b['price'];
}

usort($array, "cmp");
print_r($array);

Output:

Array
(
    [1] => Array
        (
            [price] => 8800.50
            [product] => product 2
        )

    [0] => Array
        (
            [price] => 1000.50
            [product] => product 1
        )

    [2] => Array
        (
            [price] => 200.0
            [product] => product 3
        )
)