Discussion on the use of php functions serialize of and unserialize of

  • 2021-07-13 04:53:25
  • OfStack

php function serialize ():

This function, which serializes the data and returns a storable string, is useful for storing or passing the value of PHP without losing its type and structure. So we often see such a structure in cms database.

1, we encapsulate the complex or large amount of data and do not need to be stored separately into a multi-dimensional array, convert it into a string through serialize (), and then store it in the database. When necessary, we will take it out and convert it into an array for reuse, while taking it out and converting it into an array is unserialize () of php, and there is an un in front. Direct example:


$a=array(" Week "," Full "," And "," Individual "," Blog ","www.ofstack.com"," Zhou Manhe "," Personal blog ");
$b=serialize($a);
print_r($b);
echo "<br/>";
$c=unserialize($b);
print_r($c);

The output is:


// Pass by serialize The data obtained after serialization is also stored in the database 
a:8:{i:0;s:3:" Week ";i:1;s:3:" Full ";i:2;s:3:" And ";i:3;s:6:" Individual ";i:4;s:6:" Blog ";i:5;s:20:"www.ofstack.com";i:6;s:9:" Zhou Manhe ";i:7;s:12:" Personal blog ";}
 
// Pass by unserialize() Deserialized data, and the previous $a Array structure 1 Like it 
Array ( [0] =>  Week  [1] =>  Full  [2] =>  And  [3] =>  Individual  [4] =>  Blog  [5] => www.ofstack.com [6] =>  Zhou Manhe  [7] =>  Personal blog  )

In the last example of a complex 1-point 2-dimensional array:


$a1=array(
  'name'=>array(" Week "," Full ",' And '),
  'name_weburl'=>array(" Zhou Manhe ","www.ofstack.com"),
  'all'=>array(' Zhou Man and his personal blog '=>'www.ofstack.com')
);
$b1=serialize($a1);
print_r($b1);
echo "<br/>";
$c1=unserialize($b1); 
print_r($c1);

The output is:


// Pass by serialize The data obtained after serialization is also stored in the database 
a:3:{s:4:"name";a:3:{i:0;s:3:" Week ";i:1;s:3:" Full ";i:2;s:3:" And ";}s:11:"name_weburl";a:2:{i:0;s:9:" Zhou Manhe ";i:1;s:20:"www.ofstack.com";}s:3:"all";a:1:{s:21:" Zhou Man and his personal blog ";s:20:"www.ofstack.com";}}
 
// Pass by unserialize() Deserialized data, and the previous $a Array structure 1 Like it 
Array ( [name] => Array ( [0] =>  Week  [1] =>  Full  [2] =>  And  ) [name_weburl] => Array ( [0] =>  Zhou Manhe  [1] => www.ofstack.com ) [all] => Array ( [ Zhou Man and his personal blog ] => www.ofstack.com ) )


Related articles: