Reputation: 141
When uploading images via HTTP I get the following array. How can I sort them by the size of the images in descending order, so the biggest size images would be uploaded the first and the smallest size the last?
Array
(
"name" => Array
(
[0] => 1.jpg
[1] => 2.jpg
[2] => 3.jpg
)
["type"] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
)
["tmp_name"] => Array
(
[0] => e7d31fc0
[1] => qsdf0sdf
[2] => s0sdfsfs
)
["error"] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
["size"] => Array
(
[0] => 20000
[1] => 30000
[2] => 40000
)
)
As a result, the output should be as follows:
Array
(
"name" => Array
(
[0] => 3.jpg
[1] => 2.jpg
[2] => 1.jpg
)
["type"] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
)
["tmp_name"] => Array
(
[0] => s0sdfsfs
[1] => qsdf0sdf
[2] => e7d31fc0
)
["error"] => Array
(
[0] => 0
[1] => 0
[2] => 0
)
["size"] => Array
(
[0] => 40000
[1] => 30000
[2] => 20000
)
)
Upvotes: 0
Views: 66
Reputation: 141
Based on Selim Mahmud's answer, I solved the solution:
$files = $_FILES['formFieldName'];
$sizes = $files['size'];
arsort($sizes); //sort in descending order but will preserve the keys
$files2 = array();
$i = 0;
foreach ($sizes as $key => $size) {
$files2['name'][$i] = $files['name'][$key];
$files2['type'][$i] = $files['type'][$key];
$files2['tmp_name'][$i] = $files['tmp_name'][$key];
$files2['error'][$i] = $files['error'][$key];
$files2['size'][$i] = $size;
$i++;
}
Upvotes: 0
Reputation: 892
I suppose, you will process those files in a foreach loop.
How about the code below?
//get files in array
$files = $_FILES['formFieldName'];
$sizes = $files['size'];
arsort($sizes); //sort in descending order but will preserve the keys
foreach ($sizes as $key => $size) {
$fileName = $files['name'][$key];
$fileSize = $size;
$fileType = $files['type'][$key];
$fileTmpName = $files['tmp_name'][$key];
$fileError = $files['error'][$key];
}
Upvotes: 1