How to sort Multidimensional Array
Posted: Sun May 08, 2005 3:47 pm
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.
And per the PHP manual, I should be able to easily sort it by using usort.
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!
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);
}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";
}
?>Any help and/or sample code would be great.
Thank you!