Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a multidimensional associative array

Status
Not open for further replies.

dcnguyen

Technical User
Mar 22, 2005
54
US
Argh...I swear I've read about 20 articles on usort, but can't find the answer to what must be a common dilemma:

I have an array that is formatted as such:

Code:
Array
(
    [0] => Array
        (
            [title] => Dog
            [2000] => 278
            [2007] => 50
       

        )

    [1] => Array
        (
            [title] => Cat
            [2000] => 41
            [2007] => 740
 

        )

    [2] => Array
        (
            [title] => Monkey
            [2000] => 378
            [2007] => 65
       

        )
)

And what I want to do is give the user some radio buttons so that they can pick which field to sort by, and also whether to do it ascending or descending. I understand how usort works, but in order to use it, I have to do something like:
Code:
function compar($a, $b) {
       return strnatcmp($a["title"], $b["title"]);
}

usort($array, 'compar');

How do I work with usort so I can enter in other variables that dictate by which attribute the array is sorted by, so I don't have to write a bunch of comparison functions and make different calls to usort?
 
Assuming that the user's sort-column choice is submitted in $_POST['sort_column'] and sort direction in $_POST['sort_direction'] and that $_POST['sort_direction'] will contain 'ASC' for ascending and 'DESC' for descending sort order.

Then something like:

Code:
function compar($a, $b)
{
   $retval = 0;
   switch ($_POST['sort_column'])
   {
      case 'title':
         $retval = strnatcmp($a['title'], $b['title']);
         break;

      case '2000':
         $retval = strnatcmp($a['2000'], $b['2000']);
         break;

      //  Additional cases here
   }

   if ($_POST['sort_direction'] == 'DESC)
   {
      $retval *= -1;
   }

   return $retval;
}

usort($array, 'compar');

Might get you somewhere near where you want.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Thanks, that worked. Hoped for a built-in function, but whatever does the job.
 
A sorting routine must take into account the datastructure on which it operates. How would the programmers of the PHP engine know about your user-defined datastructure?



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top