按自定义字母对数组字符串类型的键进行排序? [英] Sort array string-type keys by a custom alphabet?

查看:62
本文介绍了按自定义字母对数组字符串类型的键进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按php中的键对数组进行排序,但是我使用的字母不是普通的英语字母-这是一个自行创建的字母.这可能吗?

I want to sort arrays by key in php, but the alphabet that I'm using is not the normal English alphabet -- it's 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] 的数组应位于末尾.

So if I sort this array following my alphabet then the array with the key [=k_0] should be at the end.

推荐答案

您可以使用 usort()函数并提供自己的排序逻辑.

You can use the usort() function and provide your own sorting logic.

有关示例,请参见 php.net .

编辑:使用 uksort ,而不是 usort .参见 http://www.php.net/manual/zh/function.uksort.php .谢谢@Darien!

Edit: use uksort, not usort. See http://www.php.net/manual/en/function.uksort.php. Thanks @Darien!

php.net的一个稍作修改的示例-添加了 $ alphabet 映射的原始代码:

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";
}

这篇关于按自定义字母对数组字符串类型的键进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆