开发者

Sort array string-type keys by a custom alphabet?

开发者 https://www.devze.com 2023-03-13 05:02 出处:网络
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?

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?

My alphabet is:

$alphabet = "AjawbpfmnrhHxXsSqkgtTdD =";

The array is like this:

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
    开发者_如何学Python   )
  [sqA_1] => Array(
       [0] => DI.6,18 &dwA-nTr& @nswt@
       [1] => ra
       [2] => sqA
       [3] => Sfj,t
       [4] => =s
       [5] => r
       )
   );

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


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

See php.net for an example.

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

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


Given your $alphabet = "AjawbpfmnrhHxXsSqkgtTdD";, and assuming that A<j<a, etc, per your comment, transform each key in the alternative alphabet to a series in the known alphabet, e.g. use a mapping like:

  your alphabet: AjawbpfmnrhHxXsSqkgtTdD
 'real'alphabet: abcdefghijklmnopqrstuvw

So the key 'Ajaw' => 'abcd', and 'fmnr' => 'ghij', etc. This then turns your keys into something you can sort using conventional php functions. You'd need some way to handle characeters not present in your original alphabet though.

Something like that might work - you'd need two transform functions (from your alphabet to 'real' alphabet and vice versa), and then a comparator for e.g. uksort.

My two cents - thanks for clarifying the original question.


Fortunately, your custom alphabet does not have more characters than the list of single-byte latin letters, so translating is a very simple and readable process.

I recommend that you set up a translation array before you begin sorting, then translate/normalize the keys for the purpose of sorting.

Code: (Demo)

$array = [
    '=k_0' => ['test1'],
    'aA_2' => ['test2'],
    'sqA_1' => ['test3'],
    '=kj_0' => ['test4'],
    'awA_2' => ['test5'],
    '= D_1' => ['test6'],
    'sq A_1' => ['test7'],
    'sqA_2' => ['test8'],
];

$trans = ['AjawbpfmnrhHxXsSqkgtTdD =', 'abcdefghijklmnopqrstuvwxy'];

uksort(
    $array,
    function ($a, $b) use ($trans) {
        return strtr($a, ...$trans) <=> strtr($b, ...$trans);
    }
);
var_export($array);

Output:

array (
  'aA_2' => 
  array (
    0 => 'test2',
  ),
  'awA_2' => 
  array (
    0 => 'test5',
  ),
  'sqA_1' => 
  array (
    0 => 'test3',
  ),
  'sqA_2' => 
  array (
    0 => 'test8',
  ),
  'sq A_1' => 
  array (
    0 => 'test7',
  ),
  '=k_0' => 
  array (
    0 => 'test1',
  ),
  '=kj_0' => 
  array (
    0 => 'test4',
  ),
  '= D_1' => 
  array (
    0 => 'test6',
  ),
)

From PHP7.4, the syntax can be reduced using arrow function syntax.

uksort(
    $array,
    fn($a, $b) => strtr($a, ...$trans) <=> strtr($b, ...$trans)
);


After feedback from @mickmackusa I have updated my example to work with uksrot and answer the question fully

$order = str_split("AjawbpfmnrhHxXsSqkgtTdD");

uksort($arr, function ($a, $b) use ($order) {
    $posA = array_search($a, $order);
    $posB = array_search($b, $order);
    return $posA - $posB;
});

http://sandbox.onlinephpfunctions.com/code/9b6f39b30dcc932517bbe82608dd8a0c8d35b3da

-- original response with usort--

You can use usort() with a custom order array like so

$arr = array("w","b","m","n","x","x","z","T","T","A","A");

$order = array("A","j","a","w","b","p","f","m","n","r","h","H","x","X","s","S","q","k","g","t","T","d","D"," ","=");
    usort($arr, function ($a, $b) use ($order) {
        $posA = array_search($a, $order);
        $posB = array_search($b, $order);
        return $posA - $posB;
    });

(you could probably just explode the $order string so it's nicer)

I actually just came across this answer which explains it better, and handles if a value is not inside the order array.

And a working example http://sandbox.onlinephpfunctions.com/code/3934aafe93377ec18549d326d6551608436242a7


<?php
$arr = [8,10,12,18,20,7,4,6,2,20,0]; //take array

 $a= sortasc($arr); // call function

function sortasc($arr){


    for($i=0;$i<=count($arr);$i++){
            for($j=1;$j<=count($arr)-1;$j++){

                         if($arr[$j-1]>$arr[$j]){

                        $temp = $arr[$j];
                        $arr[$j]= $arr[$j-1];
                        $arr[$j-1] = $temp;
                    }
        }
    }
        return $arr;
}

?>


See this code:

<?php

$arr = array('wr' => 1, 'wrS' => 6, 'wr,w' => 3, 'wr.w' => 4, 'wr-qA' => 2, 'wrs' => 5);

function compare_by_alphabet(array $alphabet, $str1, $str2)
{
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    $c = min($l1, $l2);

    for ($i = 0; $i < $c; $i++)
    {
        $s1 = $str1[$i];
        $s2 = $str2[$i];
        if ($s1===$s2) continue;
        $i1 = array_search($s1, $alphabet);
        if ($i1===false) continue;
        $i2 = array_search($s2, $alphabet);
        if ($i2===false) continue;
        if ($i2===$i1) continue;
        if ($i1 < $i2) return -1;
        else return 1;
    }
    if ($l1 < $l2) return -1;
    elseif ($l1 > $l2) return 1;
    return 0;
}

function compare_keys_by_alphabet($a, $b)
{
    static $alphabet = array('-', ',', '.', 'A', 'j', 'a', 'w', 'b', 'p', 'f', 'm', 'n', 'r', 'h', 'H', 'x', 'X', 's', 'S', 'q', '‌​k', 'g', 't', 'T', 'd', 'D', '=', '/', '(', ')', '[', ']', '<', '>', '{', '}', '\'', '*', '#', 'I', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '&', '@');
    return compare_by_alphabet($alphabet, $a, $b);
}

uksort($arr, 'compare_keys_by_alphabet');

print_r($arr);

Result:

Array
(
    [wr] => 1
    [wr-qA] => 2
    [wr,w] => 3
    [wr.w] => 4
    [wrs] => 5
    [wrS] => 6
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号