/**
*对数组按username从左至右匹配排序,username一样则按cardid从大到小排序
*/
$list = array(
0=>array('cardid'=>1001,'username'=>'zhangsan'),
1=>array('cardid'=>1002,'username'=>'zhangsanfeng'),
2=>array('cardid'=>1003,'username'=>'SBzhangsan'),
3=>array('cardid'=>1005,'username'=>'SBzhangsanisyou'),
4=>array('cardid'=>1007,'username'=>'zhangsan'),
);
匹配字符串:$q = 'zhangsan';
排序后的结果应该为
$list = array(
0=>array('cardid'=>1007,'username'=>'zhangsan'),
1=>array('cardid'=>1001,'username'=>'zhangsan'),
2=>array('cardid'=>1003,'username'=>'zhangsanfeng'),
3=>array('cardid'=>1005,'username'=>'SBzhangsanisyou'),
4=>array('cardid'=>1007,'username'=>'SBzhangsan'),
);
------解决方案--------------------
SQL好使不
- SQL code
SELECT * FROM table WHERE username LIKE '%zhangsan%' ORDER BY LOCATE('zhangsan',username) ASC , cardid DESC
------解决方案--------------------
人家要对数组排序,那就对数组排序呗
- PHP code
$list = array( 0=>array('cardid'=>1001,'username'=>'zhangsan'), 1=>array('cardid'=>1002,'username'=>'zhangsanfeng'), 2=>array('cardid'=>1003,'username'=>'SBzhangsan'), 3=>array('cardid'=>1005,'username'=>'SBzhangsanisyou'), 4=>array('cardid'=>1007,'username'=>'zhangsan'), ); $q = 'zhangsan'; foreach($list as $v) { $r1[] = $v['cardid']; list($r2[], $r3[]) = explode($q, $v['username']); } array_multisort($r2, $r3, $r1, SORT_DESC, $list); print_r($list);
------解决方案--------------------
楼主给的结果有悖于自己的描述噢。
- PHP code
"sort.php" 29L, 801C written [User:root Time:02:58:29 Path:/home/liangdong/php]$ php sort.php Array ( [4] => Array ( [cardid] => 1007 [username] => zhangsan ) [1] => Array ( [cardid] => 1002 [username] => zhangsanfeng ) [0] => Array ( [cardid] => 1001 [username] => zhangsan ) [3] => Array ( [cardid] => 1005 [username] => SBzhangsanisyou ) [2] => Array ( [cardid] => 1003 [username] => SBzhangsan ) ) [User:root Time:02:58:31 Path:/home/liangdong/php]$ cat sort.php <?php $list = array( array('cardid'=>1001,'username'=>'zhangsan'), array('cardid'=>1002,'username'=>'zhangsanfeng'), array('cardid'=>1003,'username'=>'SBzhangsan'), array('cardid'=>1005,'username'=>'SBzhangsanisyou'), array('cardid'=>1007,'username'=>'zhangsan'), ); $name = "zhangsan"; uasort($list, function($left, $right) { global $name; $lndx = strpos($left['username'], $name); $rndx = strpos($right['username'], $name); $lid = $left['cardid']; $rid = $right['cardid']; if ($lndx === false && $rndx !== false || $lndx !== false && $rndx === false) { // 不包含名字的算小的 return $lndx === false ? -1 : 1; } if ($lndx == $rndx) { return $rid - $lid; } else { return $lndx - $rndx; } }); print_r($list); ?>