PHP array sorting problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jojonage
Forum Newbie
Posts: 9
Joined: Fri Nov 13, 2009 9:10 pm

PHP array sorting problem

Post 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!!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP array sorting problem

Post by requinix »

Write a function to sort two items and use it with usort.
jojonage
Forum Newbie
Posts: 9
Joined: Fri Nov 13, 2009 9:10 pm

Re: PHP array sorting problem

Post by jojonage »

thanks for your reply,

but how the function should look like to sort 2 items??
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP array sorting problem

Post 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.
jojonage
Forum Newbie
Posts: 9
Joined: Fri Nov 13, 2009 9:10 pm

Re: PHP array sorting problem

Post by jojonage »

thanks for the advise!!
I will check with the examples
jojonage
Forum Newbie
Posts: 9
Joined: Fri Nov 13, 2009 9:10 pm

Re: PHP array sorting problem

Post 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";
}
?>
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP array sorting problem

Post 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.
Post Reply