• 序列化(转)


    PHP序列化功能大家可能用的比较多,也比较常见,当你需要把数据存到数据库或者文件中是,你可以利用PHP中的serialize() 和 unserialize()方法来实现序列化和反序列化,代码如下: 
     
    Php代码 
    1. // 一个复杂的数组  
    2. $myvar = array(  
    3. ‘hello’,  
    4. 42,  
    5. array(1,’two’),  
    6. ‘apple’  
    7. );  
    8. // 序列化  
    9. $string = serialize($myvar);  
    10. echo $string;  
    11. /* 输出 
    12. 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”;} 
    13. */  
    14. // 反序例化  
    15. $newvar = unserialize($string);  
    16. print_r($newvar);  
    17. /* 输出 
    18. Array 
    19. ( 
    20. [0] => hello 
    21. [1] => 42 
    22. [2] => Array 
    23. ( 
    24. [0] => 1 
    25. [1] => two 
    26. ) 
    27. [3] => apple 
    28. ) 
    29. */  
     
     
    如何序列化成json格式呢,放心,php也已经为你做好了,使用php 5.2以上版本的用户可以使用json_encode() 和 json_decode() 函数来实现json格式的序列化,代码如下: 
     
    Php代码 
    1. // a complex array  
    2. $myvar = array(  
    3. ‘hello’,  
    4. 42,  
    5. array(1,’two’),  
    6. ‘apple’  
    7. );  
    8. // convert to a string  
    9. $string = json_encode($myvar);  
    10. echo $string;  
    11. /* prints 
    12. ["hello",42,[1,"two"],”apple”] 
    13. */  
    14. // you can reproduce the original variable  
    15. $newvar = json_decode($string);  
    16. print_r($newvar);  
    17. /* prints 
    18. Array 
    19. ( 
    20. [0] => hello 
    21. [1] => 42 
    22. [2] => Array 
    23. ( 
    24. [0] => 1 
    25. [1] => two 
    26. ) 
    27. [3] => apple 
    28. ) 
    29. */ 
  • 相关阅读:
    Day20:Decorator and Metaclass
    Day19:hasattribute;getattribute;seattributet;delattribute
    Day18:polymorphic and reflection
    Day17:call the base class
    ACL权限
    内置函数
    用户配置文件-影子文件
    用户配置文件-用户信息文件
    脚本安装包
    定义函数
  • 原文地址:https://www.cnblogs.com/xingmeng/p/3198623.html
Copyright © 2020-2023  润新知