Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

Sorting 2D associative arrays in PHP

July 13th, 2009  |  Published in php

Surprisingly, it took me a long time to find this solution so I decided to post it for anyone who had a situation similar to mine.

Let’s say you have the following 2D associative array in PHP of fruits and their corresponding prices and you want to have them sorted by price:

$fruits = array
(
    [0] => array
        (
            ['product'] => 'banana',
            ['price']     => 2.99
        ),
    [1] => array
        (
            ['product'] => 'apple',
            ['price']     => 1.99
        ),
    [2] => array
        (
            ['product'] => 'durian',  //these smell by the way - i do not know how people can like them =)
            ['price']     => 19.99
        ),
    [3] => array
        (
            ['product'] => 'starfruit', //not too stinky but still stinky nonetheless
            ['price']     => 5.99
        )
);


The answer to this one involves the use of the PHP function, usort, which allows users to define their own comparison function for sorting arrays of all shapes and sizes.

For this example, our function would need to be defined as the following if we wanted to have the prices descending:

function sortDescending ($a, $b)
{
    if ($a['price'] == $b['price']) {
        return 0;
    }
    return ($a['price'] > $b['price']) ? -1 : 1;
}

Here is the slightly different version of the function for an ascending sort:

function sortAscending ($a, $b)
{
    if ($a['price'] == $b['price']) {
        return 0;
    }
    return ($a['price'] < $b['price']) ? -1 : 1;
}

To put it all together in a descending sort, we have the following:

function sortDescending ($a, $b)
{
    if ($a['price'] == $b['price']) {
        return 0;
    }
    return ($a['price'] > $b['price']) ? -1 : 1;
}
usort($fruits, "sortDescending");
 
foreach ($fruits as $fruit) {
    echo $fruit['product'] . ": " . $fruit['price'] . "\n";
}

This would give us the following output:

durian: 19.99
starfruit: 5.99
banana: 2.99
apple: 1.99

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • drei on Simulate a button click via JavaScript
  • Subhee on How to count values with MySQL queries
  • Russell Day on How to hide, show, or toggle your div
  • phi on How to hide, show, or toggle your div
  • bornholy on How to hide, show, or toggle your div

Archives

Categories

  • javascript
  • mysql
  • php

Tag Cloud

add addition and subtraction calculator checkboxes checkEmail content demo demo content div id document getelementbyid dynamic Dynamically dynamic content emailRegEx find form getElementById html javascript input buttons input object input text javascript javascript code javascript demo javascript email javascript function javascript functions loop through menu multiplication mysql mysql query onClick onclick event query regex remove removeChild removeElement replace simulate styling valid email address verification verifyEmail

©2010 Random Snippets