问题
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