php: Sort a multidimensional array by value
2020-01-18 00:00:00
IN1
,
2023-04-10 14:16:30
IN1
say you want to sort the following array by the value of mainType
.
array $aData
$aData = array(
0 => array(
'name' => 'abc',
'size' => 7000,
'type' => 'image/png',
'mainType' => 'image',
),
1 => array(
'name' => 'document',
'size' => 25000,
'type' => 'application/pdf',
'mainType' => 'application',
)
);
sort method
using php's usort
command here will do the job.
// Sort array by values of mainType
usort($aData, function($a, $b) {
return $a['mainType'] <=> $b['mainType'];
});
Result
The array is ascending sorted by the values of mainType
.
var_dump($aData);
array(2) {
[0]=> array(4) {
["name"]=>
string(8) "document"
["size"]=>
int(25000)
["type"]=>
string(15) "application/pdf"
["mainType"]=>
string(11) "application"
}
[1]=> array(4) {
["name"]=>
string(3) "abc"
["size"]=>
int(7000)
["type"]=>
string(9) "image/png"
["mainType"]=>
string(5) "image"
}
}