Issue getting array to sort alphabetically

Hi,
    I have a select statement which pulls the content from my database.  one of the fields has several entities per field (names of people) separated by a comma, to which I use an explode routine and form a select drop down box for users to choose the name of the person they want.....

Here's the code for the select statement:

SELECT * FROM maindata

Open in new window


And here is the code making up the select box - which works great, it just doesn't sort....

<?php
echo "<select name='personID' size='1' style='font-family: Arial; font-size: 20pt; border:solid 1px #000000; border-width: 1px'>";
   echo "<option selected='selected' value='allpeople'>See all People</option>";
   while ($list = mysql_fetch_assoc($result)) {

	$people = array_filter( explode(",", $list['People']), 'strlen' );
    	    sort($people);  
      foreach($people as $person) {
		   
         echo "<option value='$person'>$person</option>";
      } 

   } // end while 
echo "</select>";
?>

Open in new window


Can anyone help?

Thanks
damianb123Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
Maybe people names are capitalized? try this:

sort($people, SORT_NATURAL | SORT_FLAG_CASE)

Open in new window

0
damianb123Author Commented:
Hi Marco,  the names of the people are in this format:

Mr H Hues, Mr D Winter, Mr J Tominson, Mr E Langeldt, Mr K Ran, Mr S Ahmed, Mr P Wong, Mr I Ching, Mr F Hirani

I would expect any sort to go by the initial i.e. H, D, J etc. so Mr D winter, Mr E Langeldt etc.

But even with your code above like this, it still doesn't seem to work:

   while ($list = mysql_fetch_assoc($result)) {

	$people = array_filter( explode(",", $list['People']), 'strlen' );
    	    sort($people, SORT_NATURAL | SORT_FLAG_CASE);  
      foreach($people as $person) {

Open in new window


Am I doing something wrong?  Thanks
0
Ray PaseurCommented:
There is a natcasesort() function in PHP, but it seems that you would want to sort by last name. then by initials (honorifics and titles are rarely sorted, but are more often ordered by rank - I can't see a good way to automate that).

Can we rely on some variant of the example here as a suitable test case?

Mr H Hues, Mr D Winter, Mr J Tominson, Mr E Langeldt, Mr K Ran, Mr S Ahmed, Mr P Wong, Mr I Ching, Mr F Hirani
0
damianb123Author Commented:
Hi Ray,  to be honest sorting by the initial would suffice, just to try and get it in some sort of order.   It doesn't seem to matter what I try though, it fails to sort.

Can you help?
0
Ray PaseurCommented:
See if this makes sense.  The "array of objects" is a very useful data structure.  We cannot use an array with last-name keys because there could be duplicated last names, and duplicated keys would cause the array to overwrite the data of the earlier identical keys.  So we have to create the usort() structure to be sure of accurate output.  The conditional around the creation of the usort() callback prevents a duplicate function name and allows us to reuse the main function over and over.
http://iconoun.com/demo/temp_damianb123.php

<?php // demo/temp_daminab123.php

/**
 * See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28645980.html
 */
error_reporting(E_ALL);
echo '<pre>';


// TEST DATA FROM THE POST AT E-E, AUGMENTED WITH SOME EDGE CASES
$data = <<<EOD
Mr H Hues, Mr D Winter, Mr J Tominson, Mr E Langeldt, Mr K Ran, Mr S Ahmed, Mr P Wong, Mr I Ching, Mr F Hirani,
Doctor No, The X-Men, Hillary Rodham Clinton, Disgraced Ex-President Richard M. Nixon, Big Bird, Madonna, Mr X Ran
EOD;


// A FUNCTION TO SORT BY APPROPRIATE NAME ORDER
function sort_names( $names, $return_array = TRUE )
{
    // MAKE AN ARRAY FROM THE STRING LIST OF NAMES
    $arr = explode(',', $names);

    // SANITIZE EACH OF THE ARRAY ELEMENTS INTO A SORTABLE OBJECT
    $objs = [];
    foreach ($arr as $name)
    {
        $obj = new StdClass;
        $parts = explode(' ', $name);
        $obj->last = end($parts);
        $obj->name = trim($name);
        $obj->last .= $obj->name;

        // COLLECT THE SORTABLE OBJECTS HERE
        $objs[] = $obj;
    }

    // CONDITIONALLY DEFINE A FUNCTION TO COMPARE BY LAST NAMES
    if (!function_exists('compare_name'))
    {
        function compare_name($a, $b)
        {
            if     ($a->last == $b->last) return 0;
            return ($a->last <  $b->last) ? -1 : 1;
        }
    }

    // SORT AND PREPARE THE RETURN DATA
    usort($objs, 'compare_name');
    $new = [];
    foreach ($objs as $obj)
    {
        $new[] = $obj->name;
    }

    // RETURN AN ARRAY OR A STRING
    if ($return_array) return $new;
    return implode(', ', $new);
}


// SHOW THE TEST DATA
var_dump($data);


// SORT THE NAMES AND SHOW THE RESULTS
$list = sort_names($data);
print_r($list);

echo PHP_EOL;

// SORT THE NAMES AND SHOW THE RESULTS IN A STRING
$list = sort_names($data, FALSE);
print_r($list);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.