This code works great, until something is case sensitive. I've tried using strnatcasecmp instead of the cmp, and it grabs the whole string not the last name. any suggestions on how to write this better?

for example the current order is:
Aaron Carson
Adam Davidson
Jen Hennings
ektor bluemouth


I want ektor bluemouth to be on top.

foreach($connected->posts as $p) {
$lastname = explode(' ', $p->post_title);
if(sizeof($lastname) == 1) {$p->lastname = $lastname[0];}
if(sizeof($lastname) == 2) {$p->lastname = $lastname[1];}
if(sizeof($lastname) == 3) {$p->lastname = $lastname[2];}
}                           
usort($connected->posts, 'cmp');

1 Answers

0
atoms On

I would do something like this

$aPosts = array(
    array('post_title' => 'Aaron Carson'),
    array('post_title' => 'Adam Davidson'),
    array('post_title' => 'Jen Hennings'),
    array('post_title' => 'ektor bluemouth'),
);

$aOrderedPosts = array();


foreach($aPosts as $iPos => $p){
    $a = explode(' ', $p['post_title']);
    // cast the last name to lowercase and assign by reference the post
    $aOrderedPosts[strtolower($a[1])] =& $aPosts[$iPos];
    }

var_dump($aOrderedPosts);
// perform a key sort
ksort($aOrderedPosts);
var_dump($aOrderedPosts);

It could be adapted to work with your data format

$aOrderedPosts = array();

foreach($connected->posts as $iPos => $p){
    $a = explode(' ', $p->post_title);
    $aOrderedPosts[strtolower($a[1])] =& $connected->posts[$iPos];
}

ksort($aOrderedPosts);
var_dump($aOrderedPosts);

Best to create $aOrderedPosts when you create/read in the post objects from DB. Additionally I would create it as a property of the connection class.