How to sort Multidimensional Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

How to sort Multidimensional Array

Post by Benjamin »

Hi,

I am trying to figure out the best and most efficient way to sort a multidimensional array. Data is stored in the array using the following code.

Code: Select all

// BUILD FILE LIST
// LOOP THROUGH ALL FILES IN SPECIFIED DIRECTORY

$FileID = "-1"; // start with -1 first loop will cause it to start at 0

if ($handle = opendir($FileSystemSafePath))
  {
  while (false !== ($FileName = readdir($handle)))
    {
    if (HideIt($FileName) != true)
      {
      if (is_file($FileSystemSafePath . $FileName))
        {
          $FileID++;
          $FileInformation[$FileID]["ActualFileName"] = $FileName;
          $FileInformation[$FileID]["FileNameNoExtension"] = RemoveFileExtension($FileName);
          $FileInformation[$FileID]["PrettyName"] = CreatePrettyName($FileInformation[$FileID]["FileNameNoExtension"]);
          $FileInformation[$FileID]["FileExtension"] = GetFileExtension($FileName);
          $FileInformation[$FileID]["FileSize"] = GetFileSize($FileSystemSafePath,$FileName);
          $FileInformation[$FileID]["FileDescription"] = AssignFileDescription($FileInformation[$FileID]["FileExtension"]);
          $FileInformation[$FileID]["FileModificationDate"] = date("m/d/Y g:i:s A", filemtime($FileSystemSafePath . $FileName));
        }
      } 
    }
  closedir($handle); 
  }
And per the PHP manual, I should be able to easily sort it by using usort.

Code: Select all

<?php
function cmp($a, $b) 
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
My question is how do I tell it to sort in ascending or descending order, and what would the cmp function look like. Also how would I tell it what fields to sort by?

Any help and/or sample code would be great.

Thank you!
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

This is the one time I've found PHP's dynamic function creation to be fantastically useful.

Code: Select all

function itemsort($items,$key){
    $compare = create_function('$a,$b','
        if ($a["'.$key.'"] == $b["'.$key.'"]) {
            return 0;
        } else {
            return ($a["'.$key.'"] > $b["'.$key.'"]) ? -1 : 1;
        }
    ');
    usort($items,$compare);
    return $items;
}
To control the asc/desc sorting you'd need to pass in another value and swap the -1 and 1 returned by the dynamic function based on it.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Thank you very much! That code solved about 10 problems that I anticipated. My only question now is how do I call that function.

Lets say I want to sort the multidimensional array by the filesize. Would I call it like this?

Code: Select all

$SortedArray = itemsort($FileInformation,"FileSize");
Also, 2nd question in line 6 of the code above, can the ? -1 : 1; be replaced with variables like ? $first : $second;

Thanks for the help!!
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

That usage is spot on.

You can change the -1 and 1 bit. They always have to be -1 and 1, but you can swap them over. Look up usort() in the PHP manual, it's explained fairly well in there.

One thing though, if you're going to be doing this a lot during the course of a script I'd create the sort functions as proper ones rather than dynamically making them on the fly. For the sake of speed.
Post Reply