2

I'm trying to use redis with multidimensional array by using HMSET.
My array looks like this.

Array
(
    [t] => Hello
    [a] => This
    [c] => key
    [b] => 23
    [data] => Array
        (
            [1] => some value
            [more] => value
        )

)

Is there any way I can store data in this format in the redis using predis library.

2
  • my Question was to add multidimensional array by using hash, if we serialise and store then it will be string, and we wont be able to sort or query into it. Commented May 23, 2012 at 11:05
  • That naturally is not possible. In your case you could serialze the data key only, and keep the rest as-is - if it helps. If not, you need to further on normalize the array structure. See en.wikipedia.org/wiki/Database_normalization Commented May 23, 2012 at 13:04

2 Answers 2

4

A better way to do this is by json_encode your array in PHP and store it as set in Redis

$string = json_encode(Array
(
    [t] => Hello
    [a] => This
    [c] => key
    [b] => 23
    [data] => Array
        (
            [1] => some value
            [more] => value
        )   
));
Sign up to request clarification or add additional context in comments.

Comments

3

Yes, Redis is able to store strings and PHP is able to serialize (multidimensional) array to strings.

The serialize function in the example can be used for that exact job, but is only exemplary, you can use any serialization method that serializes your data into a (binary) string.

For example you can make use of JSON (json_encode), XML or in some cases just implode might be fitting.

$string = serialize(Array
(
    [t] => Hello
    [a] => This
    [c] => key
    [b] => 23
    [data] => Array
        (
            [1] => some value
            [more] => value
        )

));

$cmdSet = $redis->createCommand('set');
$cmdSet->setArgumentsArray(array('thisispredisdoingredis', $string));

2 Comments

does not this serialize and unserialize decrease performance?
Redis doesn't speak PHP so you need to send it in a format you can store in Redis. Two contesters would be to serialize as a PHP object (results in a PHP specific string, see answer) or as JSON (also a string). Serialization always takes time but it's probably negligible, when important (and to be sure), do some tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.