我怎么可以用自定义排序的字母在PHP中的数组? [英] How can I sort arrays in php by a custom alphabet?
本文介绍了我怎么可以用自定义排序的字母在PHP中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在PHP关键字数组排序。但我使用的字母是不正常的英文字母,而是一种自我创造的字母表。这可能吗?
I want to sort arrays by key in php. but the alphabet I'm using is not the normal English alphabet, but a self created alphabet. Is this possible?
我的字母是
$alphabet = "AjawbpfmnrhHxXsSqkgtTdD =";
数组是这样的:
Array (
[=k_0] => Array(
[0] => DI.3,2 &dwA-nTr& @Hrw@
[1] => mA
[2] => =k
[3] => Sfj,t
[4] => =k
[5] => pXr
)
[aA_2] => Array(
[0] => DI.7,4 &dwA-nTr& @Hrw-smA-tA,wj@
[1] => snD
[2] => aA
[3] => Sfj,t
[4] => jt
[5] => jt,w
)
[sqA_1] => Array(
[0] => DI.6,18 &dwA-nTr& @nswt@
[1] => ra
[2] => sqA
[3] => Sfj,t
[4] => =s
[5] => r
)
);
所以,如果我按照我的字母与键排序的数组这个数组 [= K_0]
应该是在年底。
推荐答案
您可以使用 usort()
功能,并提供自己的排序逻辑。
You can use the usort()
function and provide your own sorting logic.
请参阅 php.net 一个例子。
修改:使用 uksort
,而不是 usort
。请参见 http://www.php.net/manual/en/function.uksort。 PHP 。感谢@Darien!
Edit: use uksort
, not usort
. See http://www.php.net/manual/en/function.uksort.php. Thanks @Darien!
从php.net稍微修改的例子 - 原来code与 $字母
映射补充说:
A slightly modified example from php.net - the original code with an $alphabet
mapping added:
function cmp($a, $b)
{
// custom sort order - just swapps 2 and 3.
$alphabet = array (1 => 1, 2 => 3, 3 => 2, 4 => 4, 5 => 5, 6=> 6);
if ($alphabet[$a] == $alphabet[$b]) {
return 0;
}
return ($alphabet[$a] < $alphabet[$b]) ? -1 : 1;
}
$a = array(3 => 'c' , 2 => 'b', 5 => 'e', 6 => 'f', 1=>'a');
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
这篇关于我怎么可以用自定义排序的字母在PHP中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文