0

In my project, I want to store array data into redis.

Here I use PHP.

First, It connects to redis successfully. And then I defined a array which name should be info_g_1.

Last, I use mset function to store this arry.

Here is my php code:

<?php
$redis_obj = \common\Datasource::getRedis('instance1');//connect to redis successfully
$id = '1';
$r_goods = 'info_g_' . $id;
$r_goods = array(
 'sys_status' => 'one',
 'num_user' => 'two'
);

$redis_obj->mset($r_goods);

But unlucky, It works fail. Thers is no info_g_1 data in my redis.

    $redis_obj->sadd('info_g_'.$id,'one');
    $redis_obj->sadd('info_g_'.$id,'two');

and fetch data:

    $redis_obj->smembers('info_g_'.$id); //can get one and two.

But this way, I am not sure whether one belongs to sys_status or num_user.

Who can help me?

4
  • 1
    mset sets data, r_goods does not contain info_g_1. What's your question about? Commented Jun 28, 2018 at 7:01
  • you need to set somthing like this $redis->mset(array('yourKEY' => 'yourValue')); Commented Jun 28, 2018 at 7:04
  • As per the above code, if you search for 'sys_status' then you if find the value 'one' Commented Jun 28, 2018 at 7:05
  • @DsRaj, I want to set a array, not a key-value. If i choose $redis->mset(array('yourKEY' => 'yourValue')); There will be many keys in redis. And it is not allowed Commented Jun 28, 2018 at 8:16

1 Answer 1

1

The value in variable $r_goods is overwritten by array in next line in following code:

$r_goods = 'info_g_' . $id;
$r_goods = array(
 'sys_status' => 'one',
 'num_user' => 'two'
);

The actual value in $r_goods is:

array(
     'sys_status' => 'one',
     'num_user' => 'two'
    );

Also you can set it as:

$redis_obj->set('info_g_' . $id, 'value to store');

Update: To add multiple key-value pairs, mset can be used as set:

$redis_obj->mset($r_goods);

But if want to store array as values corresponding to key. Then need to json_encode array first & then set as follows:

$redis_obj->set('key', json_encode(array('sys_status' => 'one', 'num_user' => 'two')));

And can be retrieved as:

$array = json_decode($redis_obj->get('key'), true);

This reason behind this is, redis store only strings no other data type.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I want to set a array not a key-value. So set function can not fix my problem
Answer Updated!

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.