此代码非常有用,直到某些内容区分大小写为止。我试过使用strnatcasecmp而不是cmp,它抓住了整个字符串而不是姓氏。有关如何更好地编写此代码的任何建议?
例如,当前订单为:
亚伦·卡森
亚当·戴维森(Adam Davidson)
詹·亨宁斯
ektor bluemouth
我希望ektor bluemouth居于首位。
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');
答案 0 :(得分:0)
我会做这样的事情
它可以适应您的数据格式
$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);
从数据库创建/读取post对象时,最好创建$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);
。另外,我将其创建为$aOrderedPosts
类的属性。