usesort在由explode函数抓取的区分大小写的字符串中不起作用

问题描述 投票:1回答:1

此代码非常有效,直到某些内容区分大小写。我尝试过使用strnatcasecmp而不是cmp,它抓住整个字符串而不是姓氏。关于如何更好地写这个的任何建议?

例如,当前的订单是: 亚伦卡森 亚当戴维森 Jen Hennings 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');
php wordpress sorting
1个回答
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);

它可以适应您的数据格式

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

最好在创建/读取DB中的post对象时创建$aOrderedPosts。另外我会把它创建为connection类的属性。

© www.soinside.com 2019 - 2024. All rights reserved.