Zulakis
Zulakis

Reputation: 8384

php custom sort function numeric

I am having a custom sort-funktion wich I use with usort:

function cmp($wert_a, $wert_b) {
$a = $wert_a["name"];
$b = $wert_b["name"];

if ($a == $b) {
   return 0;
}

return ($a < $b) ? -1 : +1; 
}

Now when I am having a array like this:5a,10b,6c,HR9,44x it sorts it into 10b,44x,5a,6c,HR9.

I would like to have it sorted like 5a,6c,10b,44x,HR9

How can this be achieved?

Edit: One thing i didn't really mention (I did in code but not in text) is that it is a multi-dimensional array like this:

$array[0]["name"] = "5b";
$array[0]["..."] = "other values";
$array[1]["name"] = "10a";
$array[1]["..."] = "other values";

Using natsort and friends i cannot sort it like this.

Upvotes: 2

Views: 388

Answers (3)

Douglas.Sesar
Douglas.Sesar

Reputation: 4430

Well for every item in the array except HR9, the natsort() function in php would handle the sorting pretty well. It disregards non-numeric characters and sorts by the number characters as if they were numeric.

here is the documentation on natsort(). http://us.php.net/natsort

$array = array(5a,10b,6c,HR9,44x);

natsort($array);

the new order should now be:

5a,6c,HR9,10b,44x

after this you could use your sorting function and only sort if the first character of one of the strings is non-numeric

In regards to your multi-dimensional array:

$temp_array = array();
foreach($array as $key => $value):

$temp_array[$key] = $value['name'];


endforeach;

natsort($temp_array);

this will give you an ordered associative array with the keys being the original array's element number and the values being the 'name'

you could

Upvotes: 0

Florian Eckerstorfer
Florian Eckerstorfer

Reputation: 1526

If you want to sort characters in their natural order (a is before H) you can use natcasesort. Consider the following array:

$array = array('5a', '10b', '6c', 'HR9', '44x', 'a9');

Using natsort:

Array
(
    [0] => 5a
    [2] => 6c
    [1] => 10b
    [4] => 44x
    [3] => HR9
    [5] => a9
)

Using natcasesort:

Array
(
    [0] => 5a
    [2] => 6c
    [1] => 10b
    [4] => 44x
    [5] => a9
    [3] => HR9
)

Edit: You can see in the output, that the indices stay the same even after the sort. Thus to sort a associative array you can create a one-dimensional copy and access the associative array with its indices. Don't forget to use foreach and not for when iterating through the sorted array.

Upvotes: 1

rationalboss
rationalboss

Reputation: 5389

I suggest that you just use natsort(). It behaves the same way as what you are trying to create.

To sort mult-dimensional arrays, refer to this: http://www.php.net/manual/en/function.array-multisort.php#61976

function array_key_multi_sort($arr, $l , $f='strnatcasecmp')
{
    usort($arr, create_function('$a, $b', "return $f(\$a['$l'], \$b['$l']);"));
    return($arr);
}

Upvotes: 5

Related Questions