zoukankan      html  css  js  c++  java
  • php操作JSON格式数据

    知识点:

    1、JSON数据格式介绍

    2、对数据编码成JSON格式

    3、对JSON数据进行解码,并操作

    JSON数据格式表示方式如下:

    { "programmers": [

      { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },

      { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },

      { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }

      ],

      "authors": [

      { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },

      { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },

      { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }

      ],

      "musicians": [

      { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },

      { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }

      ] }

    用php将数据编码成JSON格式:

    <?php  
    //php中用数组表示JSON格式数据
    $arr = array(
    'firstname' => iconv('gb2312', 'utf-8', '非诚'),
    'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
    'contact' => array(
    'email' =>'fcwr@dibaye.com',
    'website' =>'http://www.dibaye.com',
    )
    );
    //将数组编码成JSON数据格式
    $json_string = json_encode($arr);
    //JSON格式数据可直接输出
    echo $json_string;
    ?>

    需要指出的是,在非UTF-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用 gb2312编写PHP代码,那么就需要将包含中文的内容使用iconv或者mb转为UTF-8再进行json_encode。

    输出:(JSON格式)

    {"firstname":"\u975e\u8bda","lastname":"\u52ff\u6270","contact":{"email":"fcwr@dibaye.com","website":"http:\/\/www.dibaye.com"}}

    用php对JSON数据进行解码并处理:

    <?php  
    //php中用数组表示JSON格式数据
    $arr = array(
    'firstname' => iconv('gb2312', 'utf-8', '非诚'),
    'lastname' => iconv('gb2312', 'utf-8', '勿扰'),
    'contact' => array(
    'email' =>'fcwr@dibaye.com',
    'website' =>'http://www.dibaye.com',
    )
    );
    //将数组编码成JSON数据格式
    $json_string = json_encode($arr);
    //将JSON格式数据进行解码,解码后不是JSON数据格式,不可用echo直接输出
    $obj = json_decode($json_string);
    //强制转化为数组格式
    $arr = (array) $obj;
    //按数组方式调用里面的数据
    echo iconv('utf-8','gb2312',$arr['firstname']);
    echo '</br>';
    //输出数组结构
    print_r($arr);
    ?>

    输出:

    非诚
    Array ( [firstname] => 闈炶瘹 [lastname] => 鍕挎壈 [contact] => stdClass Object ( [email] => fcwr@dibaye.com [website] => http://www.dibaye.com ) )

    推荐一个自己业余时间开发的网盘搜索引擎,360盘搜www.360panso.com

  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/eczhou/p/2296085.html
Copyright © 2011-2022 走看看