• json_encode和json_decode


    1. json_encode

    (1)以下实例演示了如何将 PHP 数组转换为 JSON 格式数据:

    <?php
       $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
       echo json_encode($arr);
    ?>

    以上代码执行结果为:

    {"a":1,"b":2,"c":3,"d":4,"e":5}


    (2)以下实例演示了如何将 PHP 对象转换为 JSON 格式数据:

    <?php
       class Emp {
           public $name = "";
           public $hobbies  = "";
           public $birthdate = "";
       }
       $e = new Emp();
       $e->name = "sachin";
       $e->hobbies  = "sports";
       $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
       $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));
    
       echo json_encode($e);
    ?>

    以上代码执行结果为:

    {"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}

    2.
    json_decode
    PHP json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量。

    以下实例演示了如何解码 JSON 数据:

    <?php
       $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    
       var_dump(json_decode($json));//将json转化为对象
       var_dump(json_decode($json, true));//将json转化成数组
    ?>

    以上代码执行结果为:

    object(stdClass)#1 (5) {
        ["a"] => int(1)
        ["b"] => int(2)
        ["c"] => int(3)
        ["d"] => int(4)
        ["e"] => int(5)
    }
    
    array(5) {
        ["a"] => int(1)
        ["b"] => int(2)
        ["c"] => int(3)
        ["d"] => int(4)
        ["e"] => int(5)
    }
     
  • 相关阅读:
    双屏显示器
    Cheat Engine Tutorial v3翻译Cheat Engine 6.1 tutorial(3)
    [转]VC6创建UNICODE版Windows程序
    fread
    [转]回调函数在MFC中的使用
    [转]C++ 虚函数表解析
    [转]C/C++返回内部静态成员的陷阱
    [转]EVC 中 include 的错误
    【rgw压缩】
    【ceph | 运维】rgw重置
  • 原文地址:https://www.cnblogs.com/liujiaq/p/5818187.html
Copyright © 2020-2023  润新知