dongzi3805 2018-06-28 06:57
浏览 952
已采纳

如何在PHP中将数组数据存储到redis中

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?

  • 写回答

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:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵