如何使用 php serialize() 和 unserialize()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8641889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:08:59  来源:igfitidea点击:

How to use php serialize() and unserialize()

php

提问by Istiaque Ahmed

My problem is very basic.

我的问题很基本。

I did not find any example to meet my needs as to what exactly serialize()and unserialize()mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.

我没有找到任何示例来满足我对 php 中的确切含义serialize()unserialize()含义的需求?他们只是举了一个例子 - 序列化一个数组并以无法解释的格式显示输出。通过他们的行话很难理解基本概念。

EDIT:

编辑:

<?php

$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);

?>

output:

输出:

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

我无法理解第二个输出。除此之外,任何人都可以举例说明我需要在使用之前序列化一个 php 数组的情况吗?

回答by deceze

A PHP array or object or other complex data structurecannot be transported or stored or otherwise used outside of a running PHP script. If you want to persistsuch a complex data structure beyond a single run of a script, you need to serializeit. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serializeis just a formatto express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.

PHP 数组或对象或其他复杂的数据结构不能在运行的 PHP 脚本之外传输、存储或以其他方式使用。如果您想在一次脚本运行之后持久化如此复杂的数据结构,则需要对其进行序列化。这只是意味着将结构放入一个“较低的公分母”中,该结构可以由 PHP 以外的事物处理,例如数据库、文本文件、套接字。标准的 PHP 函数serialize只是表达这种东西的一种格式,它将数据结构序列化为 PHP 独有的字符串表示形式,并且可以使用unserialize. 但是还有许多其他格式,例如 JSON 或 XML。



Take for example this common problem:

以这个常见问题为例:

How do I pass a PHP arrayto Javascript?

如何将 PHP数组传递给 Javascript?

PHP and Javascript can only communicate via strings. You can pass the string "foo"very easily to Javascript. You can pass the number 1very easily to Javascript. You can pass the boolean values trueand falseeasily to Javascript. But how do you pass this array to Javascript?

PHP 和 Javascript 只能通过字符串进行通信。您可以"foo"非常轻松地将字符串传递给 Javascript。您可以1非常轻松地将数字传递给 Javascript。你也可以传递布尔值true,并false容易为JavaScript。但是如何将这个数组传递给 Javascript?

Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 ) 

The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

答案是序列化。对于 PHP/Javascript,JSON 实际上是更好的序列化格式:

{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }

Javascript can easily reverse this into an actual Javascript array.

Javascript 可以轻松地将其反转为实际的 Javascript 数组。

This is just as valid a representation of the same data structure though:

不过,这对于相同数据结构的表示同样有效:

a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}

But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:

但几乎只有 PHP 使用它,其他地方几乎不支持这种格式。
不过,这很常见,也得到了很好的支持:

<array>
    <element key='1'>elem 1</element>
    <element key='2'>elem 2</element>
    <element key='3'>elem 3</element>
</array>

There are many situations where you need to pass complex data structuresaround as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

在许多情况下,您需要将复杂的数据结构作为字符串传递。将任意数据结构表示为字符串的序列化解决了如何做到这一点。

回答by tipico

PHP serialize() unserialize() usage

PHP serialize() 反序列化() 用法

http://freeonlinetools24.com/serialize

http://freeonlinetools24.com/serialize

echo '<pre>';
// say you have an array something like this 
$multidimentional_array= array(
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 4, 7) 
       ),
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 5, 7) 
       ),
    array(
        array("rose", 1.25, 15),
        array("daisy", 0.75, 25),
        array("orchid", 8, 7) 
    )
);

// serialize 
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);

Which gives you an output something like this

这给你一个这样的输出

a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}

again if you want to get the original array back just use PHP unserialize() function

再次,如果您想取回原始数组,只需使用 PHP unserialize() 函数

$original_array=unserialize($serialized_array);
var_export($original_array);

I hope this will help

我希望这个能帮上忙

回答by xdazz

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize()does. And unserialize()does the reverse thing.

当你想让你的 php 值可存储时,你必须把它变成一个字符串值,这就是serialize()所做的。而unserialize()做相反的事情。

回答by Manikandan

<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b);
print_r($c);

Run this program its echo the output

运行这个程序,它的回显输出

a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}



这里


a=数组大小


i=数组个数


s=数组值大小


you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use.

您可以使用序列化将数据数组存储在数据库中,
并且可以检索和未序列化要使用的数据。

回答by alex

Most storage mediums can store stringtypes. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

大多数存储介质都可以存储字符串类型。它们不能直接存储诸如数组或对象之类的 PHP 数据结构,也不应该直接存储,因为这会将数据存储介质与 PHP 耦合。

Instead, serialize()allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

相反,serialize()允许您将这些结构之一存储为字符串。它可以从它的字符串表示中反序列化unserialize()

If you are familiar with json_encode()and json_decode()(and JSON in general), the concept is similar.

如果您熟悉json_encode()and json_decode()(以及一般的 JSON),那么这个概念是相似的。

回答by Avnish alok

Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

请!请!请!不要序列化数据并将其放入您的数据库中。Serialize 可以以这种方式使用,但这缺少关系数据库的要点和数据库引擎中固有的数据类型。这样做会使数据库中的数据不可移植、难以阅读,并且会使查询复杂化。如果您希望您的应用程序可移植到其他语言,例如假设您发现您想在应用程序的某些部分使用 Java,而在其中使用 Java 是有意义的,那么序列化将成为臀部的痛点。您应该始终能够查询和修改数据库中的数据,而无需使用第三方中介工具来操作要插入的数据。

it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

它使维护代码、具有可移植性问题的代码以及更难以迁移到其他 RDMS 系统、新模式等的数据变得非常困难。它还有一个额外的缺点,即基于以下其中一项搜索数据库变得混乱您已序列化的字段。

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.

这并不是说 serialize() 没用。这不是... 使用它的好地方可能是包含数据密集型操作结果的缓存文件,例如。还有很多其他的......只是不要滥用序列化,因为下一个出现的人会有维护或迁移的噩梦。

A good example of serialize() and unserialize() could be like this:

serialize() 和 unserialize() 的一个很好的例子可能是这样的:

$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");

Unserialize on the page

在页面上反序列化

if($_GET['x']) {
   // unpack serialize and encoded URL
   $_POST = unserialize(base64_decode($_GET['x']));
}

回答by MrGlass

From http://php.net/manual/en/function.serialize.php:

http://php.net/manual/en/function.serialize.php

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

生成值的可存储表示。这对于在不丢失类型和结构的情况下存储或传递 PHP 值非常有用。

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

本质上,它需要一个 php 数组或对象并将其转换为字符串(然后您可以根据需要传输或存储该字符串)。

Unserialize is used to convert the string back to an object.

Unserialize 用于将字符串转换回对象。

回答by DevWL

Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.

基本上,当您序列化数组或对象时,您只需将其转换为有效的字符串格式,以便您可以轻松地将它们存储在 php 脚本之外。

  1. Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
    • user personalization
  1. 使用 serialize 将对象的状态保存在数据库中(以 User 类为例)接下来反序列化数据以将先前的状态加载回对象(方法不是序列化程序您需要包含对象类才能使用它)
    • 用户个性化

Note for object you should use magic __sleep and __wakeup methods. __sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

注意对象你应该使用魔法 __sleep 和 __wakeup 方法。__sleep 由 serialize() 调用。sleep 方法将从您要保留的对象中返回一组值。

__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

__wakeup 由 unserialize() 调用。唤醒方法应该采用未序列化的值并在对象中初始化它们。

For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)

为了在 php 和 js 之间传递数据,您可以使用 json_encode 将 php 数组转换为有效的 json 格式。或者其他方式 - 使用 JSON.parese() 将输出数据(字符串)转换为有效的 json 对象。您可能希望这样做以利用本地存储。(离线数据访问)

回答by DevWL

Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.

我可以。假设我们需要跟踪您的系统意味着在您的系统中有多个管理员和子管理员,所有这些都可以插入或更新或编辑任何信息。稍后您需要知道是谁进行了更改。为了解决这个问题,你需要序列化。

  **Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:

  history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)

I hope this will help you.

我希望这能帮到您。

回答by X 47 48 - IR

preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');