sort multidimensional array in alphabetical order of the keys in PHP [duplicate]

孤街浪徒 提交于 2019-12-12 06:58:32

问题


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:


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
        )

)


来源:https://stackoverflow.com/questions/56869250/sort-multidimensional-array-in-alphabetical-order-of-the-keys-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!