Page 1 of 1
PHP array sorting problem
Posted: Fri Nov 13, 2009 9:13 pm
by jojonage
Hello,
I have a problem on sorting an array list
for instant, the array list is as follow:
$testing = array("AB1", "AC4", "DE3", "HG2");
how can I sort the array list, so that it looks like this:
AB1
HG2
DE3
AC4
What I would like to do is to ignore the first 2 characters and sort only by the numbers
many thanks!!
Re: PHP array sorting problem
Posted: Fri Nov 13, 2009 9:47 pm
by requinix
Write a function to sort two items and use it with
usort.
Re: PHP array sorting problem
Posted: Fri Nov 13, 2009 9:57 pm
by jojonage
thanks for your reply,
but how the function should look like to sort 2 items??
Re: PHP array sorting problem
Posted: Fri Nov 13, 2009 10:09 pm
by requinix
jojonage wrote:but how the function should look like to sort 2 items??
It should look like something that takes two items (as function arguments) and decides which one should come first in the sorted array.
cmp_function
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Look at the examples.
Re: PHP array sorting problem
Posted: Fri Nov 13, 2009 10:24 pm
by jojonage
thanks for the advise!!
I will check with the examples
Re: PHP array sorting problem
Posted: Sun Nov 15, 2009 7:10 pm
by jojonage
it works great!thanks!
Here is the example
Code: Select all
<?php
function cmp($a, $b)
{
$a = ereg_replace('^(a|an|the) ', '', $a);
$b = ereg_replace('^(a|an|the) ', '', $b);
return strcasecmp($a, $b);
}
$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
Re: PHP array sorting problem
Posted: Sun Nov 15, 2009 8:40 pm
by requinix
One change I would make: the ereg functions are going away in favor of PCRE.
Code: Select all
function cmp($a, $b)
{
$a = preg_replace('/^(an?|the) /i', '', $a);
$b = preg_replace('/^(an?|the) /i', '', $b);
return strcasecmp($a, $b);
}
And a minor change to the expression for simplicity.