php: Sort a multidimensional array by value

2020-01-18 2020-01-18 11:48:07 PHP,array,EN

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"
    }
}

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".