zoukankan      html  css  js  c++  java
  • 转载--PHP json_encode() 和json_decode()函数介绍

    转自:http://www.nowamagic.net/php/php_FunctionJsonEncode.php

    转自:http://www.jb51.net/article/30489.htm

    1.json_encode

    在 php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它。
    这个函数的功能是将数值转换成json数据存储格式。
    <?php
    $arr = array
    (
    'Name'=>'希亚',
    'Age'=>20
    );
    $jsonencode = json_encode($arr);
    echo $jsonencode;
    ?>
    程序运行结果如下:
    {"Name":null,"Age":20}
    json_encode 函数中中文被编码成 null 了,Google 了一下,很简单,为了与前端紧密结合,Json 只支持 utf-8 编码,我认为是前端的 Javascript 也是 utf-8 的原因。
    <?php
    $array = array
    (
    'title'=>iconv('gb2312','utf-8','这里是中文标题'),
    'body'=>'abcd...'
    );
    echo json_encode($array);
    ?>
    这个程序的运行结果为:
    {"title":"u8fd9u91ccu662fu4e2du6587u6807u9898","body":"abcd..."}

    -----{["标题1"]:["标题内容"],["标题2"]:["标题内容"],XXXXXX}

    2.json_decode() 

    (PHP 5 >= 5.2.0, PECL json >= 1.2.0) 
    json_decode — 对 JSON 格式的字符串进行编码 
    说明 
    mixed json_decode ( string $json [, bool $assoc ] ) 
    接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 
    参数 
    json 
    待解码的 json string 格式的字符串。 
    assoc 
    当该参数为 TRUE 时,将返回 array 而非 object 。
    返回值 
    Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned. 

    范例 

    Example #1 json_decode() 的例子 

    <?php 
    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
    var_dump(json_decode($json)); 
    var_dump(json_decode($json, true)); 
    ?> 

    output #1:

    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) 

    Example #2 json_decode() 的例子 

    $data='[{"Name":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000","QQNo":""},{"Name":"a1","Number":"123","Contno":"000","QQNo":""}]'; 
    echo json_decode($data,true); 

    output#2:

    Array ( [0] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => stdClass Object ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) ) 

    echo json_decode($data,true); 

    Array ( [0] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [1] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) [2] => Array ( [Name] => a1 [Number] => 123 [Contno] => 000 [QQNo] => ) ) 

  • 相关阅读:
    iOS之MRC和ARC
    给tableView的cell上加长按转发,复制、、等功能
    时间格式相关
    Xcode7,消失的pin菜单(Editor->pin)
    UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
    监听iPhone的通话状态之---CoreTelephony.framework
    iOS中一些系统通知名字集合
    iOS中的程序的五种状态
    Objective-C基础之@synthesize, @dynamic
    Objective-C基础之category extension
  • 原文地址:https://www.cnblogs.com/siliconvalley/p/3250037.html
Copyright © 2011-2022 走看看