php - 使用 Predis,如何设置(即存储)多维关联数组?

标签 php redis predis

我是following this guide开始使用 PHP 中的 Predis。在本指南中,他们提供了 set() 函数来存储键值对:

//sets message to contain "Hello world"
$redis->set(';message';, ';Hello world';);

现在我要使用 predis 缓存的数据是一个来自 MongoDB 数据库的多维关联数组,它看起来像

allRowsDataArray = array(
  row0 = array(
    key0 = value0,
    key1 = value1,
    ...so on
  ),
  row1 = array(
    field0 = value0,
    field1 = value1,
    ...so on
  ),
  ...so on
)

所以为了在缓存中保存这个数组,当我这样做的时候

$redis->set('allRowsDataArray', $allRowsDataArray);

我得到这个异常/错误:

Warning: strlen() expects parameter 1 to be string, array given in /var/www/html/testProject/plugins/predis/predis/src/Connection/StreamConnection.php on line 390
Notice: Array to string conversion in /var/www/html/testProject/plugins/predis/predis/src/Connection/StreamConnection.php on line 391
Fatal error: Uncaught Predis\Response\ServerException: ERR Protocol error: invalid bulk length in /var/www/html/testProject/plugins/predis/predis/src/Client.php:370 Stack trace: #0 /var/www/html/testProject/plugins/predis/predis/src/Client.php(335): Predis\Client->onErrorResponse(Object(Predis\Command\StringSet), Object(Predis\Response\Error)) #1 /var/www/html/testProject/plugins/predis/predis/src/Client.php(314): Predis\Client->executeCommand(Object(Predis\Command\StringSet)) #2 /var/www/html/testProject/plugins/predis/index.php(110): Predis\Client->__call('set', Array) #3 {main} thrown in /var/www/html/testProject/plugins/predis/predis/src/Client.php on line 370

所以问题是我错过了什么?我该如何解决这个问题?

最佳答案

Set 方法期望值为字符串。使用 json_encode()保存数据。

$redis->set('allRowsDataArray', json_encode($allRowsDataArray));

并使用json_decode()Redis 中检索。

关于php - 使用 Predis,如何设置(即存储)多维关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405461/

相关文章:

php - MySQL中使用Limit而不使用Order By结果是否一致

php - 上传多个文件 pdo

Django:缓存图像

javascript - 在异步模式下使用时,redis createClient 上的 Google 云函数错误

python-3.x - 如何与 Tornado IOLoop同时运行长时间运行的阻止功能

php - Predis中使用hmset的问题

php - 为什么我在 Redis 事务中获取不到缓存数据?

php - 如何在 Yii2 中的 ActiveField 的 form-group div 中添加 css 类?

php - Redis "unknown command"错误

php - 如何获取数组中同一键的最大值