Search code examples
phparrayssortingmultidimensional-arrayalphabetical-sort

sort multidimensional array in alphabetical order of the keys in PHP


I have an array like this with alphabetical keys :

Array
(
    [0] => Array
        (
            [UserID] => 1
            [EmailAddress] => [email protected]
            [TransID] => fjhf8f7848
        )
    [1] => Array
        (
            [UserID] => 1
            [EmailAddress] => [email protected]
            [TransID] => dfsdhsdu78
        )

)

I want to sort this array in alphabetical order of the keys. Expected output is :

Array
(
    [0] => Array
        (
            [EmailAddress] => [email protected]
            [TransID] => fjhf8f7848
            [UserID] => 1
        )
    [1] => Array
        (
            [EmailAddress] => [email protected]
            [TransID] => dfsdhsdu78
            [UserID] => 2
        )

)

I tried various array sort functions but they return blank.

How do I sort such a array with alphabetical keys in alphabetic order?


Solution

  • You can use array_map and ksort,

    $result = array_map(function(&$item){
        ksort($item); // sort by key
        return $item;
    }, $arr);
    

    Demo.

    Using foreach loop,

    foreach($arr as &$item){
        ksort($item);
    }
    

    EDIT
    In that case you can use,

    foreach($arr as &$item){
        uksort($item, function ($a, $b) {
          $a = strtolower($a); // making cases linient and then compare
          $b = strtolower($b);
          return strcmp($a, $b); // then compare
        });
    }
    

    Demo

    Output

    Array
    (
        [0] => Array
            (
                [EmailAddress] => [email protected]
                [TransID] => fjhf8f7848
                [UserID] => 1
            )
    
        [1] => Array
            (
                [EmailAddress] => [email protected]
                [TransID] => dfsdhsdu78
                [UserID] => 1
            )
    
    )