本文总结一下最近项目中用到的各种排序方法,如需转载,请注明文章出处
- Yii::import('ext.SphinxClient');
- $sphinxapi = new SphinxClient();
- $sphinxapi->SetServer('127.0.0.1', 10312);
- $sphinxapi->SetConnectTimeout(3);
- $sphinxapi->SetMatchMode(SPH_MATCH_BOOLEAN);
- $sphinxapi->SetArrayResult(true);
- $sphinxapi->SetGroupBy('type', SPH_GROUPBY_ATTR,"@count desc");
- $sphinxapi->SetLimits(0, 9999, 10000);
- $result = $sphinxapi->Query('', 'main;delta');
- unset($sphinxapi);
指定了按照 @count 降序排列
- SPH_GROUPBY_ATTR,"@count desc"
有时候我们需要从数据库中找到的数据按照我们已有的数组顺序进行排列,而不是简单的根据数据表字段进行 order by
比如:
我们有一个数组 $IDArray=array(13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6);
现在需要从shop表中查找19个数据,并且让shop的id根据$IDArray中的顺序来排列
可以使用,find_in_set(id,'************')来实现
- SELECT id, name FROM shop WHERE id IN(13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6) order by find_in_set(id,'13,24,2,23,21,10,22,12,26,27,19,20,8,14,25,9,11,1,6')
- $sql = "SELECT id, name FROM shop WHERE id IN(".join(',', array_keys($IDARRAY)).") order by find_in_set(id,'".join(',', array_keys($IDARRAY))."') ";
- $rawDataAll = Yii::app()->db->createCommand($sql)->queryAll();
关于find_in_set(id,'************'),的用法扩展可以
参考:mysql中替代charindex的函数substring_index、find_in_set
把这个方法封装成一个类,在Yii项目中随意调用
- ArrayHelper::array_sort($bodyArray, 'count', 'desc')
- <?php
- class ArrayHelper extends CController
- {
- public function array_sort($arr, $keys, $type='asc')
- {
- $keysvalue = $new_array = array();
- foreach($arr AS $k=>$v)
- {
- $keysvalue[$k] = $v[$keys];
- }
- if($type == 'asc')
- {
- asort($keysvalue);
- }
- else
- {
- arsort($keysvalue);
- }
- reset($keysvalue);
- foreach ($keysvalue as $k=>$v)
- {
- $new_array[$k] = $arr[$k];
- }
- return $new_array;
- }
- }
- ?>