<?php
$redis = new redis();
$redis->connect('192.168.1.108', 6379);
$redis->flushall();
$redis->lpush('test', 31);
$redis->lpush('test', 5);
$redis->lpush('test', 2);
$redis->lpush('test', 23);
$array = array('LIMIT'=>array(0,3),"SORT"=>'DESC');
print_r($redis->sort('test',$array)); //结果:Array ( [0] => 31 [1] => 23 [2] => 5 )
?>
使用外部key进行排序
有时候你会希望使用外部的key作为权重来比较元素,代替默认的对比方法。
假设现在有用户(user)表数据如下:
复制代码 代码如下:
id name score
-------------------------------
1 tank 89
2 zhang 40
4 ying 70
3 fXXK 90
id数据保存在key名为id的列表中。
name数据保存在key名为name_{id}的列表中
score数据保存在score_{id}的key中。
复制代码 代码如下:
<?php
$redis = new redis();
$redis->connect('192.168.1.108', 6379);
$redis->flushall();
$redis->lpush('id', 1);
$redis->set('name_1', 'tank');
$redis->set('score_1',89);
$redis->lpush('id', 2);
$redis->set('name_2', 'zhang');
$redis->set('score_2', 40);
$redis->lpush('id', 4);
$redis->set('name_4','ying');
$redis->set('score_4', 70);
$redis->lpush('id', 3);
$redis->set('name_3', 'fXXK');
$redis->set('score_3', 90);
/**
* 按score从大到小排序,取得id
*/
$sort=array('BY'=>'score_*',
'SORT'=>'DESC'
);
print_r($redis->sort('id',$sort)); //结果:Array ( [0] => 3 [1] => 1 [2] => 4 [3] => 2 )
/**
* 按score从大到小排序,取得name
*/
$sort=array('BY'=>'score_*',
'SORT'=>'DESC',
'GET'=>'name_*'
);
print_r($redis->sort('id',$sort)); //结果:Array ( [0] => fXXK [1] => tank [2] => ying [3] => zhang )
/**
* 按score从小到大排序,取得name,score
*/
$sort=array('BY'=>'score_*',
'SORT'=>'DESC',
'GET'=>array('name_*','score_*')
);
print_r($redis->sort('id',$sort));
/**
*结果:Array
(
[0] => fXXK
[1] => 90
[2] => tank
[3] => 89
[4] => ying
[5] => 70
[6] => zhang
[7] => 40
))
*/
/**
* 按score从小到大排序,取得id,name,score
*/
$sort=array('BY'=>'score_*',
'SORT'=>'DESC',
'GET'=>array('#','name_*','score_*')
);
print_r($redis->sort('id',$sort));
/**
* 结果:Array
(
[0] => 3
[1] => fXXK
[2] => 90
[3] => 1
[4] => tank
[5] => 89
[6] => 4
[7] => ying
[8] => 70
[9] => 2
[10] => zhang
[11] => 40
)
*/
?>
您可能感兴趣的文章: