2013-07-17

Iterate through zset in SSDB with PHP

Views: 8465 | Add Comments

Connect to SSDB

<?php
require_once("SSDB.php");
$ssdb = new SimpleSSDB('127.0.0.1', 8888);

Generate test data

$zname = 'test';
for($i=0; $i<1000; $i++){
    $key = "k$i";
    $score = mt_rand(0, 100);
    $ssdb->zset($zname, $key, $score);
}
$size = $ssdb->zsize($zname);
echo "total $size items\n";

With this php codes, it will create a zset named zname, and insert 1000 items. Items may have same scores.

Iterate

$num = 1;
$key_start = ''; 
$score_start = ''; 
while(1){
    $items = $ssdb->zscan($zname, $key_start, $score_start, '', 10);
    if(!$items){
        break;
    }   
    foreach($items as $key=>$score){
        printf("%5d: %-5s = %5d\n", $num, $key, $score);
        // remember the max key and its score
        $key_start = $key;
        $score_start = $score;
        $num += 1;
    }   
    echo "---\n";
}

Though we know there are 1000 items in the zset in this case, but for most chances there would be more items in one zset. So we cannot get all items at once.

As demostration, we choose to get 10 items at a time, then get other 10 items after those. Repeat the same operation until we iterate through all items in the zset.

Posted by ideawu at 2013-07-17 18:42:37 Tags:

Leave a Comment