Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predis - how to use array with zadd function?

I've just started using Predis for Redis migration and I'm having trouble getting the zadd function to work with an array.

This code works:

foreach ($userIndexArr as $row) {
  $usernames[] = 0;
  $usernames[] = $row['username']; 
  $result = $this->cache->zadd('@person', 0, $row['username']);
}

This doesn't:

foreach ($userIndexArr as $row) {
  $usernames[] = 0;
  $usernames[] = $row['username']; 
}
try {
    $result = $this->cache->zadd('@person', $usernames);
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}           

And no error is thrown. Any help is much appreciated!

-J

like image 552
jt_dylan Avatar asked Oct 21 '14 00:10

jt_dylan


2 Answers

I played around with this and if you're struggling with this the following example will surely help (following the redis.io documents example):

$predis->zadd( 'myset', [ "one" => 1, "uno" => 1, "two" => 2, "three" => 3 ] )

this will result in the same sorted set as on redis' example:

ZADD myzset 1 "one"
ZADD myzset 1 "uno"
ZADD myzset 2 "two" 3 "three"

tricky part of that if you want to do this in one line in Redis you would put the scores first, like so:

ZADD myzset 1 "one" 1 "uno" 2 "two" 3 "three"

in Predis, this would work as well:

$predis->zadd( 'myset', 1, "one", 1, "uno", 2, "two", 3, "three" );
like image 184
patrick Avatar answered Sep 28 '22 00:09

patrick


When using predis you must send the member as key and the score as value

$predis->zadd('your:table', array('member' => 'score');

for examples in redis docs it would be:

$predis->zadd('myzset', array('uno' => 1, 'two' => 2);
like image 24
Marius.C Avatar answered Sep 27 '22 22:09

Marius.C