sort multidimensional array in alphabetical order

2019-09-20 09:28发布

I have an array like this with alphabetical keys :

Array
(
    [0] => Array
        (
            [UserID] => 1
            [EmailAddress] => user5@gmail.com
            [TransID] => fjhf8f7848
        )
    [1] => Array
        (
            [UserID] => 1
            [EmailAddress] => johndoe@gmail.com
            [TransID] => dfsdhsdu78
        )

)

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

Array
(
    [0] => Array
        (
            [EmailAddress] => user5@gmail.com
            [TransID] => fjhf8f7848
            [UserID] => 1
        )
    [1] => Array
        (
            [EmailAddress] => johndoe@gmail.com
            [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?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-20 09:37

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] => user5@gmail.com
            [TransID] => fjhf8f7848
            [UserID] => 1
        )

    [1] => Array
        (
            [EmailAddress] => johndoe@gmail.com
            [TransID] => dfsdhsdu78
            [UserID] => 1
        )

)
查看更多
登录 后发表回答