• <strike id="s0kuu"></strike>
  • <tr id="s0kuu"><s id="s0kuu"></s></tr>
  • <dfn id="s0kuu"></dfn>
  • <dfn id="s0kuu"></dfn>
    <fieldset id="s0kuu"><source id="s0kuu"></source></fieldset>
    <fieldset id="s0kuu"><source id="s0kuu"></source></fieldset>
  • \n
    <\/div>\n<\/body>\n

    亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

    Table of Contents
    php處理json格式數(shù)據(jù)經(jīng)典案例總結(jié),json經(jīng)典案例
    Home php教程 php手冊 php處理json格式數(shù)據(jù)經(jīng)典案例總結(jié),json經(jīng)典案例

    php處理json格式數(shù)據(jù)經(jīng)典案例總結(jié),json經(jīng)典案例

    Jun 13, 2016 am 08:39 AM
    json php

    php處理json格式數(shù)據(jù)經(jīng)典案例總結(jié),json經(jīng)典案例

    本文實(shí)例總結(jié)了php處理json格式數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

    1.json簡介:

    何為json?

    簡 單地說,JSON 可以將 JavaScript 對象中表示的一組數(shù)據(jù)轉(zhuǎn)換為字符串,然后就可以在函數(shù)之間輕松地傳遞這個字符串,或者在異步應(yīng)用程序中將字符串從 Web 客戶機(jī)傳遞給服務(wù)器端程序.

    通俗點(diǎn)講,它是一種數(shù)據(jù)的存儲格式,就像php序列化后的字符串一樣。

    它也是一種數(shù)據(jù)描述,比如:我們將一個數(shù)組序列化后存放,就可以很容易的反序列化后應(yīng)用;json也是如此,只不過它搭建的是客戶端javascript和服務(wù)器端php交互的橋梁。

    如何使用json?

    自php5.2開始及之后的版本都內(nèi)置了json的支持,主要有兩個函數(shù):

    json_encode():編碼,生成一個json字符串
    json_decode():一個解碼

    注意:經(jīng)過json_encode()函數(shù)編碼后,將返回一個json格式的字符串,如:$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';將json格式的字符串輸出,將得到一個json格式的javascript對象

    2.json案例一:

    json_encode的使用:

    <&#63;php
    $arr = array(
     'name' => '魏艷輝',
     'nick' => '為夢翱翔,
     'contact' => array(
     'email' => 'zhuoweida@163.com',
     'website' => 'http://zhuoweida.blog.tianya.cn',
     )
    );
    $json_string = json_encode($arr);
    echo $json_string;//json格式的字符串
    &#63;>
    

    結(jié)果:

    {
       "name":"\u9648\u6bc5\u946b",
       "nick":"\u6df1\u7a7a",
       "contact":
           {
             "email":"shenkong at qq dot com",
             "website":"http:\/\/www.chinaz.com"
           }
    }
    
    

    提示:輸出的數(shù)據(jù)本身就是json格式的js對象,因為沒有帶引號,所以在前臺頁面可以直接將其當(dāng)做json對象使用

    總結(jié):關(guān)聯(lián)數(shù)組是按照javascript對象來構(gòu)造的

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    3.json案例二:

    json_decode的使用:

    <&#63;php
    $arr = array(
     'name' => '魏艷輝',
     'nick' => '為夢翱翔',
     'contact' => array(
     'email' => 'zhuoweida@163.com',
     'website' => 'http://zhuoweida.blog.tianya.cn',
     )
    );
    $json_string = json_encode($arr);
    $obj = json_decode($json_string); //可以使用$obj->name訪問對象的屬性
    $arr=json_decode($json_string,true);//將第二個參數(shù)為true時將轉(zhuǎn)化為數(shù)組
    print_r($obj);
    print_r($arr);
    &#63;>
    
    

    結(jié)果:

    {
       "name":"\u9648\u6bc5\u946b",
       "nick":"\u6df1\u7a7a",
       "contact":
           {
            "email":"shenkong at qq dot com",
            "website":"http:\/\/www.chinaz.com"
           }
    }
    
    

    總結(jié):關(guān)聯(lián)數(shù)組是按照J(rèn)avaScript對象來構(gòu)造的

    提示:輸出的數(shù)據(jù)本身就是json格式的js對象,因為沒有帶引號,所以在前臺頁面可以直接將其當(dāng)做json對象使用

    分析:編碼后就要解碼,php提供了相應(yīng)的函數(shù)json_decode,執(zhí)行此函數(shù)后,將會得到一個對象或數(shù)組。

    4.json案例三:

    當(dāng)和前臺交互的時候,json的作用就顯示出來了:

    例如:javascript代碼如下:

    <script type="text/javascript">
    var obj = {
          "name":"\u9648\u6bc5\u946b",
          "nick":"\u6df1\u7a7a",
          "contact":
              {
               "email":"shenkong at qq dot com",
               "website":"http:\/\/www.chinaz.com"
              }
         };
         alert(obj.name);
    </script>
    
    

    代碼分析:上面代碼,直接將json格式數(shù)據(jù)賦給一個變量,它就變成一個javascript對象了,這樣我們可以很方便的對obj進(jìn)行遍歷

    提示:在javascript中,數(shù)組的訪問是通過索引來訪問的;對象屬性的訪問是通過 對象名.屬性名 來訪問的

    提示:輸出的數(shù)據(jù)本身就是json格式的js對象,因為沒有帶引號,所以在前臺頁面可以直接將其當(dāng)做json對象使用

    5.json案例四:json跨域的數(shù)據(jù)調(diào)用:

    例如:主調(diào)文件index.html

    <script type="text/javascript">
      function getProfile(str) {
          var arr = str;
          document.getElementById('nick').innerHTML = arr.nick;
      }
    </script>
    <body>
       <div id="nick"></div>
    </body>
    <script type="text/javascript" src="http://localhost/demo/profile.php"></script>
    
    

    例如:被調(diào)用文件profile.php

    <&#63;php
    $arr = array(
      'name' => '魏艷輝',
        'nick' => '為夢翱翔',
         'contact' => array(
             'email' => 'zhuoweida@163.com',
             'website' => 'http://zhuoweida.blog.tianya.cn',
          )
        );
    $json_string = json_encode($arr);
    echo "getProfile($json_string)";
    &#63;>
    
    

    代碼分析:當(dāng)index.html調(diào)用profile.php,json字符串生成,并作為參數(shù)傳入getProfile,然后將昵稱插入到div中 ,這樣一次跨域數(shù)據(jù)交互就完成了

    6.js如何解析服務(wù)器端返回的json字符串?

    我們在使用ajax做客戶端和服務(wù)器端交互的時候,在不適用jQuery等框架的前提下,一般的做法是讓服務(wù)器端返回一段json字符串,然后在客戶端將它解析成javascript對象。解析時用到的方法一般是eval或者是new function,而目前ie8和firefox3.1有內(nèi)置了原生的json對象。

    例1:

    var strTest='{"a":"b"}'; //轉(zhuǎn)換成JS對象
    var obj=eval("("+strTest+")") ;
    
    

    例2:

    function strtojson(strTest){
      JSON.parse(str);
    }
    
    

    7.案例五:對象的json化

    <&#63;php
    //1.對象
    class JsonTest{
      var $id = 1;
      var $name = 'heiyeluren';
      $gender = '男';
    }
    $obj = new JsonTest;
    echo json_encode($obj)."<br /> ";
    &#63;>
    
    

    瀏覽器輸出結(jié)果:

    {
      "id":1,
      "name":"heiyeluren",
      "gender":"\u7537"
    }
    
    

    結(jié)論:對象的json字符串是按照javascript對象來構(gòu)造的。無法識別中文,所有的中文字符串沒有被正確顯示出來

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    提示:輸出的數(shù)據(jù)本身就是json格式的js對象,因為沒有帶引號,所以在前臺頁面可以直接將其當(dāng)做json對象使用

    8.案例六:索引數(shù)組的json化

    <&#63;php
    $arr1 = array(1, 'heiyeluren', '男');
    echo json_encode($arr1)."<br /> ";
    &#63;>
    
    

    瀏覽器輸出結(jié)果:

    [
      1,
      "heiyeluren",
      "\u7537"
    ]
    
    

    結(jié)論:純數(shù)字索引數(shù)組的json字符串是按照javascript能夠識別的數(shù)組來存儲的,而不是按照javascript能夠識別的對象來存儲的。無法識別中文,所有的中文字符串沒有被正確顯示出來

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    9.案例七:關(guān)聯(lián)數(shù)組的json化

    <&#63;php
    $arr2 = array("id"=>1, "name"=>'heiyeluren', "gender"=>'男');
    echo json_encode($arr2)."<br /> ";
    &#63;>
    
    

    瀏覽器輸出結(jié)果:

    {
      "id":1,
      "name":"heiyeluren",
      "gender":"\u7537"
    }
    
    

    結(jié)論:關(guān)聯(lián)索引數(shù)組的json字符串是按照javascript對象的形式來構(gòu)造的。無法識別中文,所有的中文字符串沒有被正確顯示出來

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    提示:輸出的數(shù)據(jù)本身就是json格式的js對象,因為沒有帶引號,所以在前臺頁面可以直接將其當(dāng)做json對象使用

    10.案例八:對多維索引數(shù)組的進(jìn)行json化

    <&#63;php
    $arr3 = array(array(1, 'heiyeluren', '男'), array(1, 'heiyeluren', '男'));
    echo json_encode($arr3)."<br /> ";&#63;>
    
    

    瀏覽器輸出結(jié)果:

    [
      [1,"heiyeluren","\u7537"],
      [1,"heiyeluren","\u7537"]
    ]
    
    

    結(jié)論:多維數(shù)字索引數(shù)組的json字符串是按照javascript能夠識別的數(shù)組來存儲的。無法識別中文,所有的中文字符串沒有被正確顯示出來

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    提示:輸出的數(shù)據(jù)可以直接將其當(dāng)做javascript數(shù)組使用

    11.案例九:對多維關(guān)聯(lián)數(shù)組的進(jìn)行json化

    <&#63;php
    $arr4 = array(
      array("id"=>1, "name"=>'heiyeluren', "gender"=>'男'),
      array("id"=>1, "name"=>'heiyeluren', "gender"=>'男')
    );
    echo json_encode($arr4)."<br /> ";
    &#63;>
    
    

    瀏覽器輸出結(jié)果:

    [
      {"id":1,"name":"heiyeluren","gender":"\u7537"},
      {"id":1,"name":"heiyeluren","gender":"\u7537"}
    ]
    
    

    結(jié)論:多維關(guān)聯(lián)索引數(shù)組是按照外圍是JavaScript數(shù)組,中間的索引數(shù)組是對象。無法識別中文,所有的中文字符串沒有被正確顯示出來

    分析:上述案例很簡單的將一個數(shù)組json化了,需要指出的是在非utf-8編碼下,中文字符將不可被encode,結(jié)果會出來空值,所以如果你使用gb2312編碼編寫php代碼,那么就需要將包含中文的內(nèi)容使用iconv或mb系列函數(shù)轉(zhuǎn)化為utf-8后在json_encode

    提示:輸出的數(shù)據(jù)可以直接將其當(dāng)做javascript數(shù)組使用

    12.案例十:json格式的javascript對象的創(chuàng)建

    json的格式與語法:

    var jsonobject=
    {
        //對象內(nèi)的屬性語法(屬性名與屬性值是成對出現(xiàn)的)
        propertyname:value,
        //對象內(nèi)的函數(shù)語法(函數(shù)名與函數(shù)內(nèi)容是成對出現(xiàn)的)
        functionname:function(){...;}
    };
    

    注意:

    ①jsonobject -- JSON對象名稱
    ②propertyname -- 屬性名稱
    ③functionname -- 函數(shù)名稱
    ④一對大括號,括起多個"名稱/值"的集合
    ⑤屬性名或函數(shù)名可以是任意字符串,甚至是空字符串
    ⑥逗號用于隔開每對"名稱/值"對

    提示:

    ①在javascript中,數(shù)組的訪問是通過索引來訪問的; 對象屬性的訪問是通過 對象名.屬性名? 來訪問的
    ②經(jīng)過json_encode()化而的數(shù)據(jù)都是js能夠識別的格式,而經(jīng)過json_decode()化的數(shù)據(jù)都是php能夠識別的格式,這一點(diǎn)大家心里要清楚
    ③經(jīng)過json_encode()化而輸出的數(shù)據(jù)都是json格式的javascript對象,在前臺可直接將其當(dāng)做js對象使用

    另外,本站還提供了如下格式化與轉(zhuǎn)換工具方便大家使用:

    php代碼在線格式化美化工具:
    http://tools.jb51.net/code/phpformat

    在線XML/JSON互相轉(zhuǎn)換工具:
    http://tools.jb51.net/code/xmljson

    JavaScript代碼美化/壓縮/格式化/加密工具:
    http://tools.jb51.net/code/jscompress

    在線XML格式化/壓縮工具:
    http://tools.jb51.net/code/xmlformat

    更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《php文件操作總結(jié)》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《php日期與時間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

    希望本文所述對大家PHP程序設(shè)計有所幫助。

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1488
    72
    PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

    User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

    How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

    The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

    How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

    To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

    PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

    1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

    How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

    PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

    PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

    PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

    Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

    PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

    How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services Jul 25, 2025 pm 08:24 PM

    The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

    See all articles