Reputation: 4478
Well, There are many posts and questions using usort to sort array on custom pattern, but didnt find anything that matches my need. Here is the code I have so far,
$arrayToSort=array("Sabin","Anil","Cyrus","Kamal","Kesha","Bimal");
function mycmp($a, $b)
{
static $order = array('A', 'B','C',"Ke'",'Ka','R', 'S');
return array_search(substr($a,0,1), $order) - array_search(substr($b,0,1), $order);
}
usort($arrayToSort, "mycmp");
The above codes sorts $arrayToSort in following pattern
Array
(
[0] => Anil
[1] => Bimal
[2] => Cyrus
[3] => Kamal
[4] => Kesha
[5] => Sabin
)
However, if you look into my custom pattern static $order = array('A', 'B','C',"Ke'",'Ka','R', 'S');
Kesha should come before Kamal as in my pattern 'Ke' comes before 'Ka'
Again I know substr($a,0,1)
takes the first character only that's why its not working.
I also doubt that I have to take another approach to get job done, but I m not being able to figure it out.
How to sort if the element of array pattern is not consistent, i.e. some of the elements have one character while others have two? Any help will highly be appreciated. Thanks
Upvotes: 3
Views: 390
Reputation: 132018
Here is a way you can do it. This could certainly be better optimized, but you get the idea.
<?php
class Accessor {
static $order = array(
'A' => 1,
'B' => 1,
'C' => 1,
'K' => array(
'e' => 1,
'a' => 1,
),
'R' => 1,
'S' => 1
);
}
$arrayToSort=array("Kamal","Kesha","Sabin","Anil","Cyrus","Bimal");
function mycmp($a, $b, $base) {
$letter1 = $a[0];
$letter2 = $b[0];
if ($letter1 == $letter2) {
if (is_array($base[$letter1])) {
return mycmp(substr($a, 1), substr($b, 1), $base[$letter1]);
}
}
return array_search($letter1, array_keys($base)) - array_search($letter2, array_keys($base));
}
function cmp_proxy($a, $b) {
return mycmp($a, $b, Accessor::$order);
}
usort($arrayToSort, "cmp_proxy");
print_r($arrayToSort);
OUTPUT
Array
(
[0] => Anil
[1] => Bimal
[2] => Cyrus
[3] => Kesha
[4] => Kamal
[5] => Sabin
)
Upvotes: 1
Reputation: 2523
Try this
$arrayToSort=array("Sabin","Anil","Cyrus","Kamal","Kesha","Bimal");
function mycmp($a, $b)
{
static $order = array('A', 'B','C',"Ke'",'Ka','R', 'S');
return searchArray($a, $order) - searchArray($b, $order);
}
function searchArray($str,$order) {
$i = 1;
do {
$result = array_search(substr($str,0,$i++),$order);
if($result)
return $result
}while(i < strlen($str))
return -1;
}
usort($arrayToSort, "mycmp");
Upvotes: 0