Using Uasort() To Sort A Multdimensional Associative Array By One Of Its Fields

 
    <?php
$products = array( array( name=>"A", price=>4.5  ),
                   array( name=>"C", price=>5.5  ),
                   array( name=>"D", price=>2.5  ),
                   array( name=>"B", price=>2.5  )
);
function priceCmp( $a, $b ){
   if  ( $a[price] == $b[price] )
        return 0;
   if  ( $a[price] < $b[price] )
         return -1;
   return 1;
}
uasort( $products, priceCmp );
foreach ( $products as $key => $val )
     print "$key: $val[price]<br />\n";
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.