Question

I am trying to create a memberlist with all the members in the databse, however they are in there on a front name basis. So I an trying to put the surname first before printing them.

For that I wrote this function:

function surname($name){
    $exploded = explode(" ", $name);
    $num = count($exploded);

    $move = $exploded[$num - 1];
    unset($exploded[$num - 1]);
    array_unshift($exploded, $move);
    $name = implode(", ", $exploded);
    return $name;
}

And while using that I am trying to make an array of rightly called people. (because mysql sorts by front name instead of surname, so I want to sort the array aftarwards)

                $names = array();
                $sql = "SELECT * FROM Members";
                $self = mysql_query($sql);
                while ($row = mysql_fetch_array($self)) {
                    $name = $row["name"];
                    $name = surname($name);
                    array_push($names, $name);
                }               
                echo $names;

This however doesn't give anything back, which I think is because the array is being remade every loop.

So my question, is this a valid way of doing it or do I have to do something completely different?

Please help.

Was it helpful?

Solution

Something like this may work note its untested though

SELECT * FROM Members ORDER BY SUBSTRING_INDEX(name, ' ', -2)

It should select the first 2 words that appear to the right of the first space. That should allow for middle name and surname.

OK this'll work too its messy/compute heavy but works. Its horrible with loop within loop but short of fixing your db to a proper structure this is as good as you'll get (unless you wanna go into the black magic of regex.

$surnamesarray = array();
 $sql = "SELECT * FROM Members";
                $self = mysql_query($sql);
                while ($row = mysql_fetch_array($self)) {
                    $temparray = explode(" ",$row['name']);
                    $substring = "";
                    for ($i=0;$i<count($temparray);$i++) {
                     $substring .= " ".$temparray[$i];
                    }
                    $surnamesarray[] = trim($substring)
                }

// now we just array sort so 
sort($surnamesarray);
var_dump($surnamesarray);//you would now for each this array again to display i'm just dumping out here

OTHER TIPS

in your loop, change the second $name to $names[] then don't echo but print_r($names) and try deleting the array push

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top