在PHP中按字母的字母顺序对多维数组进行排序 [英] sort multidimensional array in alphabetical order of the keys in PHP
本文介绍了在PHP中按字母的字母顺序对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数组,带有字母键:
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?
推荐答案
您可以使用array_map和ksort,
You can use array_map and ksort,
$result = array_map(function(&$item){
ksort($item); // sort by key
return $item;
}, $arr);
演示.
使用foreach循环,
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
});
}
输出
Array
(
[0] => Array
(
[EmailAddress] => user5@gmail.com
[TransID] => fjhf8f7848
[UserID] => 1
)
[1] => Array
(
[EmailAddress] => johndoe@gmail.com
[TransID] => dfsdhsdu78
[UserID] => 1
)
)
这篇关于在PHP中按字母的字母顺序对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文