Using Predis, how to SET (i.e. store) a multidimensional associative array?

本秂侑毒 提交于 2020-01-30 08:24:08

问题


I am following this guide to get started with Predis in PHP. In this guide, they have given the set() function to store key value pairs:

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

Now the data I want to cache using predis is a multidimensional associative array coming from a MongoDB database, and it looks like

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

So in order to save this array in cache, when I do

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

I get this exception/error:

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

So the question is that what am I missing? How should I resolve this problem?


回答1:


Set method expect value to be string. Use json_encode() to save data.

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

And use json_decode() to retrieve from Redis.



来源:https://stackoverflow.com/questions/48405461/using-predis-how-to-set-i-e-store-a-multidimensional-associative-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!