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

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

问题描述

我想在 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/en/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天全站免登陆