Re: Sort a text string by last word before separator

From: Date: Fri, 25 Jun 2004 03:21:07 +0000
Subject: Re: Sort a text string by last word before separator
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-189023@lists.php.net to get a copy of this message
Andre Dubuc wrote:
Given a text string: $OK = "Joe Blow, William Howard Anser, Hannie Jansen, etc, etc,";
[snip]
How would I get this 'before_last' function to iterate through the initial string, so I could build a sorted list with both first and last names, sorted by last name? I can't seem to get a proper 'foreach' statement to work, nor a 'while' statement.
There are few different ways. Here's one: ------------------------------------------------------------------------------- function splitSortNames($namePartSeparator,
                        $nameSeparator,
                        $nameString)
{
    preg_match_all('/(\w+)((\s(\w+)\s)*(\s?(\w+)))*/',
                   $nameString,
                   $tmp_names,
                   PREG_SET_ORDER);
    $names = array();
    foreach ($tmp_names as $i => $name)
    {
        $tmp = array();
        if (!empty($name[6])) $tmp[1] = $name[6];
        if (!empty($name[1])) $tmp[2] = $name[1];
        if (!empty($name[4]))
        {
            $tmp[2] .= ' ' . $name[4];
        }
        $names[$name[0]] = join(', ', $tmp);
    }
    asort($names);
    $names = array_keys($names);
    return $names;
} $names = splitSortNames(' ', ', ', $OK); print_r($names); ------------------------------------------------------------------------------- To check out a few other ideas along with a short (likely inaccurate) speed test, check out http://www.thebuttlesschaps.com/sortByLast.html (there is a 'View Source' link at the bottom of the page). This code returns the names in the format in which they are given. You can speed it up a bit by having it return the names in 'lastname, firstname' format. For this, change
        $names[$name[0]] = join(', ', $tmp);
to
        $names[$i] = join(', ', $tmp);
and remove the lines:
    asort($names);
    $names = array_keys($names);
I'm really confused. I've read almost every entry on arrays/strings and searched code snippets. Almost all focus on one element arrays such "apple, orange, peach" rather than 2 or more elements such as "fancy cars, big trucks, fast dangerous motorcycles," Is it even possible to accomplish this type sort on a string? Any advice, pointers, or help will be greatly appreciated, Tia, Andre
Hopefully the code above will give you some aid--and you can probably improve on that regexp in preg_match_all(). The other 2 ways on the site have totally different methods, and different strengths and weaknesses. Maybe you can turn one of them into something useful to you. Hope this helps, Torben -- Torben Wilson <torben@php.net>

« previous php.general (#189023) next »