使用Redis存储数据数组(来自Laravel) [英] Storing an array of data using Redis (from Laravel)

查看:1706
本文介绍了使用Redis存储数据数组(来自Laravel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始与laravel合作.工作非常有趣.我已经开始使用laravel的功能.我已开始通过在系统中安装Redis服务器来使用redis,并在app/config/database.php文件中更改redis的配置.通过使用set,redis对于单个变量可以正常工作.即

I have started to work with laravel. It is quite interesting to work. I have started to use the features of laravel. I have started to use redis by install redis server in my system and change the configuration for redis in app/config/database.php file. The redis is working fine for the single variables by using set. i.e.,

$redis = Redis::connection();

$redis->set('name', 'Test');

我可以通过使用

$redis->get('name');

但是我想通过使用set函数来设置数组.如果我尝试这样做,则会出现以下错误

But i want to set the array by using set function. If i try do that getting the following error

 strlen() expects parameter 1 to be string, array given 

我尝试使用以下代码.

$redis->set('name', array(5, 10));

$values = $redis->lrange('names', array(5, 10));

如果我使用

$values = $redis->command('lrange', array(5, 10));

出现以下错误

 'command' is not a registered Redis command 

有人可以向我解释这个问题吗,redis是否有可能?...我们可以使用redis设置数组值吗?

Can any one explain me the problem and is that possible with redis?...we can set the array values using redis ?

推荐答案

已在评论中回答了此问题,但为将来访问的人们提供了更清晰的答案.

This has been answered in the comments but to make the answer clearer for people visiting in the future.

Redis与语言无关,因此它无法识别任何特定于PHP或任何其他语言的数据类型.最简单的方法是先设置serialise/json_encode数据,然后再获取unserialise/json_decode.

Redis is language agnostic so it won't recognise any datatype specific to PHP or any other language. The easiest way would be to serialise / json_encode the data on set then unserialise/json_decode on get.

使用json_encode存储数据的示例:

use Illuminate\Support\Facades\Redis;

$redis = Redis::connection();

$redis->set('user_details', json_encode([
        'first_name' => 'Alex', 
        'last_name' => 'Richards'
    ])
);

使用json_decode检索数据的示例:

use Illuminate\Support\Facades\Redis;

$redis    = Redis::connection();
$response = $redis->get('user_details');

$response = json_decode($response);

这篇关于使用Redis存储数据数组(来自Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆