$options = [
'by' => 'pattern', // 外部鍵權重模式(如 'score_*')
'limit' => [0, 10], // 分頁:偏移量、數量
'get' => 'pattern', // 獲取模式(如 'name_*'、['name_*','score_*'])
'sort' => 'asc|desc', // 排序方向
'alpha' => true, // 字母排序(非數值)
'store' => 'target_key', // 結果存儲到新鍵
];
$redis->sort('source_key', $options);
$redis = new Redis();
$redis->connect('192.168.1.108', 6379);
$redis->flushall();
// 列表數值排序
$redis->lpush('test', 1, 10, 8);
print_r($redis->sort('test'));
// Array([0]=>1, [1]=>8, [2]=>10)
// 字母排序
$redis->lpush('test', 'a', 'd', 'b');
print_r($redis->sort('test')); // [b, d, a] (按 ASCII)
print_r($redis->sort('test', ['alpha'=>true])); // [a, b, d]
// 分頁 + 降序
$redis->lpush('test', 31, 5, 2, 23);
print_r($redis->sort('test', [
'limit' => [0, 3],
'sort' => 'desc'
])); // [31, 23, 5]
場景:用戶表數據分散存儲,需按 `score` 排序獲取 `name`。
// 數據結構:
// id 列表: LRANGE id 0 -1 -> [1,2,4,3]
// name: name_{id} -> string
// score: score_{id} -> int
$redis->lpush('id', 1, 2, 4, 3);
$redis->set('name_1', 'tank'); $redis->set('score_1', 89);
$redis->set('name_2', 'zhang'); $redis->set('score_2', 40);
$redis->set('name_4', 'ying'); $redis->set('score_4', 70);
$redis->set('name_3', 'fXXK'); $redis->set('score_3', 90);
// 1. 按 score 降序獲取 id
$sort = ['by' => 'score_*', 'sort' => 'desc'];
print_r($redis->sort('id', $sort));
// [3, 1, 4, 2] (fXXK=90, tank=89, ying=70, zhang=40)
// 2. 按 score 降序獲取 name
$sort = ['by' => 'score_*', 'sort' => 'desc', 'get' => 'name_*'];
print_r($redis->sort('id', $sort));
// [fXXK, tank, ying, zhang]
// 3. 獲取多字段:name + score
$sort = ['by' => 'score_*', 'sort' => 'desc', 'get' => ['name_*', 'score_*']];
print_r($redis->sort('id', $sort));
// [fXXK, 90, tank, 89, ying, 70, zhang, 40]
// 4. 獲取 id + name + score(# 代表源鍵值)
$sort = ['by' => 'score_*', 'sort' => 'desc', 'get' => ['#', 'name_*', 'score_*']];
print_r($redis->sort('id', $sort));
// [3, fXXK, 90, 1, tank, 89, 4, ying, 70, 2, zhang, 40]
| 函數 | 用途 | 示例 |
|---|---|---|
| `keys('pattern')` | 模式匹配鍵 | `keys('user_*')` |
| `mset([k=>v,...])` | 批量設置 | `mset(['a'=>1,'b'=>2])` |
| `mget([k1,k2])` | 批量獲取 | `mget(['a','b'])` -> [1,2] |
`SORT` 是 Redis 少數支援「跨鍵關聯排序」的命令,適合簡單場景。複雜業務建議採用 **Sorted Set 作為主索引**,或將排序邏輯下沉到應用層/搜索引擎(Elasticsearch)。理解 `BY`、`GET`、`#` 三大核心參數是掌握 `SORT` 的關鍵。