Home >Backend Development >PHP Tutorial >redis saves the array (json_encode is unsuccessful, serialize is successful)
Use redis to store arrays and store them in string type.
Use PHP's own json_encode and json_decode to convert to json (failed).
PHP’s own serialization functions serialize and unserialize functions (successful).
Are there any specific differences? Can anyone tell me the principles of success and failure?
Use PHP's own json_encode and json_decode to convert to json (failed).
PHP’s own serialization functions serialize and unserialize functions (successful).
Are there any specific differences? Can anyone tell me the principles of success and failure?
You can directly print the string of
json_encode and the result of json_decode
to see.
I guess it is possible that
has missing parameters and is written as json_decode($str)
, causing the result to be an object instead of an array.
Serialization refers to converting data objects in the running environment into stream data so that it can be saved to a file or transmitted over the network for use elsewhere.
After deserialization, this stream data will be restored to a data object in the languageEvery language has its own serialization method
php has a more efficient method than serialize, which is
igbinary_unserialize()
These two methods need to install the ibginary module
Configuration when using redis
<code>$reids->setOption(Redis::OPT_SERIALIZER,Redis::SERIALIZER_IGBINARY); </code>
About serialization, take PHP as an example
<code>class Person{ private $_name = "default"; public function get_name(){ return $this->_name; } } $p = new Person; $sp = serialize($p); send2serverB($p);</code>
You serialized an object instance in server A, and you need to use the instance in service B
Of course, server B also needs to have a declaration of class Person in order to deserialize it normally
<code>function recieve_handle($sp){ $p = unserialize($p); // 反序列后, 能还原Person实例, 能使用实例的方法 // json只是种保存元数据的格式, 无法保存对象 $name = $p->get_name(); }</code>
gbk cannot be encoded