6

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

jt_dylan
  • 71
  • 1
  • 6

3 Answers3

5

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" );
patrick
  • 11,519
  • 8
  • 71
  • 80
3

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);
Marius.C
  • 700
  • 6
  • 14
0

Try below, according to this source: https://github.com/nrk/predis/blob/v1.0/src/Command/ZSetAdd.php

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

Untested, though. But I think it works, as long as you're using v1.0 =)

Niloct
  • 9,491
  • 3
  • 44
  • 57
  • I tried this but no luck. Still using the zadd in for loop. Is there a way to do this using execute raw? – jt_dylan Oct 26 '14 at 21:40
  • Check you Predis version, also issue a `MONITOR` in redis-cli to check what is the current command your code is sending. – Niloct Oct 27 '14 at 18:36
  • So, have you checked monitor command to see what's being output ? Also please tell me your Predis version. – Niloct Oct 31 '14 at 18:01
  • Hi, very sorry for the late reply. Had something a workaround so had to move on. Tried your code as is and it worked like a charm. Many thanks! – jt_dylan Apr 20 '15 at 23:55