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!!
PHP array sorting problem
Moderator: General Moderators
Re: PHP array sorting problem
Write a function to sort two items and use it with usort.
Re: PHP array sorting problem
thanks for your reply,
but how the function should look like to sort 2 items??
but how the function should look like to sort 2 items??
Re: PHP array sorting problem
It should look like something that takes two items (as function arguments) and decides which one should come first in the sorted array.jojonage wrote:but how the function should look like to sort 2 items??
Look at the examples.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.
Re: PHP array sorting problem
thanks for the advise!!
I will check with the examples
I will check with the examples
Re: PHP array sorting problem
it works great!thanks!
Here is the example
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
One change I would make: the ereg functions are going away in favor of PCRE.
And a minor change to the expression for simplicity.
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);
}