0

Possible Duplicate:
How do I sort a multidimensional array by one of the fields of the inner array in PHP?

I would like to know, how can we custom sort a multi-dimentional array. The array contains values like:-

$products = array(
    array('John', '155', 10 ),
    array( 'Paul', '151', 95 ),
    array( 'Rodger', '152', 85 )
);

In the first array, John is the name, 155 is the ID and 10 is the Price. How can I sort the whole array by Price(Highest to Lowest) and then print the data using a foreach loop?

Community
  • 1
  • 1
Pritpal
  • 3
  • 4

1 Answers1

0

you can define compare function, and use 'usort' method.

see below example.

<?php

// Comparison function
function cmp($a, $b) {
    if ($a[2] == $b[2]) {
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}

// Array to be sorted
$products = array( array( 'John', '155', 10 ),
      array( 'Paul', '151', 95 ),
      array( 'Rodger', '152', 85 ) );

// Sort array
usort($products, 'cmp');

//Print the resulting array
foreach ($products as $key=>$item) {
    echo "Name : ".$item[0]. "  ID : " .$item[1]. "  Price : ".$item[2]. "\n";
}

?>
IvoryCirrus
  • 622
  • 1
  • 4
  • 15