I have an array inside an array that has the filename, modification time and size, but I need to be able to order the array either ascending or descending by each one of these properties.
I have the following, which gets the information
//SCAN THE DIRECTORY
$directories = scandir($dir);
$directinfo = array();
foreach($directories as $directory){
if ($directory === '.' or $directory === '..') continue;
if(!stat($dir.'/'.$directory)){
} else {
$filestat = stat($dir.'/'.$directory);
$directinfo[] = array(
'name' => $directory,
'modtime' => $filestat['mtime'],
'size' => $filestat['size']
);
}
}
The array is structured as so:
Array (
[0] => Array (
[name] => 0 Organisation Details
[modtime] => 1398164749
[size] => 4096
)
[1] => Array (
[name] => 1 Permission Form
[modtime] => 1398164749
[size] => 4096
)
[2] => Array (
[name] => 6 Invoices
[modtime] => 1400802471
[size] => 4096
)
)
and then use this to output:
foreach($directinfo as $dirInfo){
foreach($dirInfo as $key=>$drInfo){
echo "Output: ".$key."=>".$drInfo."<br />";
}
}
But I need to arrange the array before this, and somehow make it so I don't need two arrays or I'm suspecting the ordered output wouldn't work.
I've looked at array_multisort
but can't figure out how this would work in this instance.
Any help with this is really appreciated.
Using example #3 on the array_multisort
manual page:
$directories = array(
array('name'=>'filec','modtime'=>'12303403434','size'=>'12401'),
array('name'=>'fileb','modtime'=>'12303403432','size'=>'12400'),
array('name'=>'filez', 'modtime'=>'12304445405','size'=>'65200')
);
// Obtain a list of columns
$name = $modtime = $size = array();
foreach ($directories as $key => $row) {
$name[$key] = $row['name'];
$modtime[$key] = $row['modtime'];
$size[$key] = $row['size'];
}
// Sort the data with name ascending, modtime ascending, size ascending
array_multisort($name, SORT_ASC, $modtime, SORT_ASC, $size, SORT_ASC, $directories);
print_r($directories);
Online demo here
You can use usort:
usort($arr, function($a,$b){
return strcmp($a['name'], $b['name']);
});
var_dump($arr);