In PHP, there is a good way to format a string and transform an array or object, that is, serialization processing.
There are two ways to serialize variables.
The following example uses the Serialize () and Unserialize () functions:
A complex array
$myvar = array (
' hello ', +,
Array (1, ' two '),
' Apple '
);
Convert to a string
$string = serialize ($myvar);
echo $string;
/* Prints
a:4:{i:0;s:5: "Hello"; I:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "Two";} I:3;s:5: "Apple";}
*
//You can reproduce the original variable
$newvar = Unserialize ($string);
Print_r ($newvar);
/* Prints
array
(
[0] => Hello
[1] =>
[2] => array
(
[0] => 1
[1 ] => two
)
[3] => Apple
)
* *
This is a native PHP serialization method.
However, thanks to JSON's popularity in recent years, support for JSON format has been added to PHP5.2.
Now you can use the Json_encode () and Json_decode () functions:
A complex array
$myvar = array (
' hello ', +,
Array (1, ' two '),
' Apple '
);
Convert to a string
$string = Json_encode ($myvar);
echo $string;
/* Prints
["Hello", 42,[1, "two"], "apple"]
*//You
can reproduce the original variable
$newvar = Json_decode ($string);
Print_r ($newvar);
/* Prints
array
(
[0] => Hello
[1] =>
[2] => array
(
[0] => 1
[1 ] => two
)
[3] => Apple
)
* *
This will be more effective, especially if it is compatible with many other languages, such as JavaScript.
Note: For complex objects, some information may be lost.
The above mentioned is the entire content of this article, I hope you can enjoy.