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'];

The array is ascending sorted by the values of mainType.

array(2) {
    [0]=> array(4) {
        string(8) "document"
        string(15) "application/pdf"
        string(11) "application"
    [1]=> array(4) {
        string(3) "abc"
        string(9) "image/png"
        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".