問題描述
我已經開始使用 Laravel.工作很有趣.我已經開始使用 Laravel 的功能了.我已經開始使用 redis
通過在我的系統中安裝 redis 服務器并更改 app/config/database.php
文件中的 redis 配置.通過使用 set
,redis 可以很好地處理單個變量.即,
$redis = Redis::connection();$redis->set('name', 'Test');
我可以通過使用獲得價值
$redis->get('name');
但我想使用 set
函數來設置數組.如果我嘗試這樣做,則會出現以下錯誤
strlen() 期望參數 1 是字符串,給定數組
我已嘗試使用以下代碼.
$redis->set('name', array(5, 10));$values = $redis->lrange('names', array(5, 10));
如果我使用
$values = $redis->command('lrange', array(5, 10));
出現以下錯誤
'command' 不是注冊的 Redis 命令
任何人都可以向我解釋這個問題嗎?redis 可以嗎?...我們可以使用 redis
設置數組值嗎?
這已經在評論中回答了,但為了讓以后訪問的人更清楚地回答.
Redis 與語言無關,因此它不會識別特定于 PHP 或任何其他語言的任何數據類型.最簡單的方法是 serialise
/json_encode
數據集,然后 unserialise
/json_decode
獲取.>
使用 json_encode
存儲數據的示例:
使用 IlluminateSupportFacadesRedis;$redis = Redis::connection();$redis->set('user_details', json_encode(['first_name' =>'亞歷克斯','姓氏' =>理查茲"]));
使用 json_decode
檢索數據的示例:
使用 IlluminateSupportFacadesRedis;$redis = Redis::connection();$response = $redis->get('user_details');$response = json_decode($response);
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');
and i could able to get the value by using
$redis->get('name');
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
I have tried by using following codes.
$redis->set('name', array(5, 10));
$values = $redis->lrange('names', array(5, 10));
and if i use
$values = $redis->command('lrange', array(5, 10));
getting the following error
'command' is not a registered Redis command
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 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.
Example to store data using json_encode
:
use IlluminateSupportFacadesRedis;
$redis = Redis::connection();
$redis->set('user_details', json_encode([
'first_name' => 'Alex',
'last_name' => 'Richards'
])
);
Example to retrieve data using json_decode
:
use IlluminateSupportFacadesRedis;
$redis = Redis::connection();
$response = $redis->get('user_details');
$response = json_decode($response);
這篇關于使用 Redis 存儲數據數組(來自 Laravel)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!