May 7, 2012

Sort an array by alphabetically by second word

Question by mdance

I am sorting a multidimensional array that contains peoples names and some information aobut them. I’m using asort($obj) to sort it alphabetically by their first names (it comes first). It works great, only now I need to sort it by their last name, rather than first. However, the name in its entirety “Joe Smith” for example is under the “name” key. I need it sorted by last name, instead of first. How can I do this?

EDIT
It seems that I went about it in the wrong way. It ended up easiest to simply assign the first and last name from the DB to separate fields, rather than the same string.

Answer by Starx

Not, so different than the previous answer. But, using a natural algorithm might be a good choice, on such situations.

$array = array( 
    array("first", "last"), 
    array("first2", "last2")
); //For an array of such format
function compare_last($a, $b) { return strnatcmp($a[1], $b[1]); } 
usort($array, 'compare_last');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!