views:

112

answers:

2

Hi all,

I got an array which contains some data like this:

$arrs = Array("ABC_efg", "@@zzAG", "@$abc", "ABC_abc")

I was trying to print the data out in this way (Printing in alphabetic order):

[String begins with character A]
ABC_abc
ABC_efg
[String begins with character other than A to Z]
@$abc
@@zzAG

I don't know how to do it.

+3  A: 

I'm going to assume you mean strings starting with a letter should appear before all other strings and all strings should otherwise be sorted in the standard order.

You use usort() and define a custom function for the ordering and ctype_alpha() to determine if something is a letter or not.

$arrs = Array("ABC_efg", "@@zzAG", "@$abc", "ABC_abc");
usort($arrs, 'order_alpha_first');

function order_alpha_first($a, $b) {
  $lenA = strlen($a);
  $lenB = strlen($b);
  $len = min($lenA, $lenB);
  $i = 0;
  while ($a[$i] == $b[$i] && $i < $len) {
    $i++;
  }
  if ($i == $len) {
    if ($lenA == $lenB) {
      return 0; // they're the same
    } else {
      return $lenA < $lenB ? -1 : 1;
    }
  } else if (ctype_alpha($a[$i])) {
    return ctype_alpha($b[$i]) ? strcmp($a[$i], $b[$i]) : -1;
  } else {
    return ctype_alpha($b[$i]) ? 1 : strcmp($a[$i], $b[$i]);
  }
}

Output:

Array
(
    [0] => ABC_abc
    [1] => ABC_efg
    [2] => @$abc
    [3] => @@zzAG
)
cletus
A: 

You write a function sortArray($array, $preset=1) that splits the $array in two arrays. ($preset should be empty by default)

The first array contains all the elements that start with no special sign, the second one contains all elements that start with a special sign. You than sort the firstArray normally (sort()) and print them, and invoke the function on the second array, passing the preset.

(something like

if ($array[i][$preset] != "@") {
array_push ($firstArray ,$array[i]);
} else {
array_push ($secondArray ,$array[i]);
}
sort($firstArray);
print($firstArray);
sortArray($secondArray, $preset++);

)

It's just what came to my mind :)

Samuel