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');