I am trying to figure out how to sort an array by filesize strings correctly. I am building an array like the one shown below and would like to sort it by the filesize column. I have looked around but havent been able to find anything that has been too helpful in sorting it.
Array (
[0] => Array (
[0] => FileName
[1] => 71.6 MB
[2] => /path/to/file/
[3] => 2018-12-08 19:31:17 )
[1] => Array (
[0] => FileName
[1] => 1.15 GB
[2] => /path/to/file/
[3] => 2018-12-08 17:36:28 )
[2] => Array (
[0] => FileName
[1] => 10.22 MB
[2] => /path/to/file/
[3] => 2018-12-08 16:13:24 )
[3] => Array (
[0] => FileName
[1] => 34.42 MB
[2] => /path/to/file/
[3] => 2018-12-08 16:24:27 )
[4] => Array (
[0] => FileName
[1] => 466.18 KB
[2] => /path/to/file/
[3] => 2018-12-08 16:31:44 )
[5] => Array (
[0] => FileName
[1] => 26.98 MB
[2] => /path/to/file/
[3] => 2018-12-08 17:34:57 )
)
I am loading data from a database and I get and add the file sizes while building the array using this function.
function format_size($size) {
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) { return('n/a'); } else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}
This is basically how I am building the array.
if ($stmt->rowCount() > 0) {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
$data_array = Array();
foreach ($iterator as $key => $row) {
$fname = $row["filename"];
$size = filesize('/path/to/file/' . $row["filename"]);
$fsize = format_size($size);
$fpath = '/path/to/file/' . $row["filename"];
$f_tstamp = $row['timestamp'];
$file_array = Array(
$fname,
$fsize,
$fpath,
$f_tstamp
);
$time[$key] = $row['timestamp'];
$data_array[] = $file_array;
}
This is how I sort by timestamps.
array_multisort($time, SORT_DESC, $data_array);
foreach ($data_array as $val) {
print $val[0];
print $val[1];
print $val[2];
print $val[3];
}
What can I do to sort it properly using the filesize strings? Thanks.