2018-06-28 06:57
浏览 733


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:

$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'


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


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?

图片转代码服务由CSDN问答提供 功能建议



首先,它成功连接到redis。 然后我定义了一个名称应该是info_g_1的数组。


这是我的PHP代码 :

 $ redis_obj = \ common \ Datasource :: getRedis('instance1'); //成功连接到redis 
 $ id ='1  '; 
 $ r_goods ='info_g_'。  $ id; 
 $ r_goods = array(
 $ redis_obj-&gt; mset($ r_goods  ); 

但不幸的是,它失败了。 Thers在我的redis中没有info_g_1数据。

  $ redis_obj-&gt; sadd('info_g _'。$ id,'one'); 
 $ redis_obj-&gt; sadd  ('info_g _'。$ id,'two'); 


  $ redis_obj  - &GT; smembers( 'info_g _' 的$ id);  //可以得到一个和两个。



  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duaeim2874 2018-06-28 07:17

    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:

         '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:


    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.

    打赏 评论

相关推荐 更多相似问题