Detailed analysis of php json instance

Source: Internet
Author: User
Tags bitmask php and php array to json php json

JSON (json_encode) encoded in PHP)
The PHP json_encode () function is used for JSON encoding in PHP. This function returns the value in JSON format. If it fails, FALSE is returned.

Syntax:

String json_encode ($ value [, $ options = 0]) parameter:
Value: The value to be encoded. This function applies only to data encoded by the UTF-8.

Options: this optional value is a bitmask consisting of JSON_HEX_TAG JSON_HEX_QUOT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, response, JSON_FORCE_OBJECT

Example

The following example demonstrates how to convert a PHP array to JSON:

The code is as follows: Copy code

<? Php
$ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
Echo json_encode ($ arr );
?>

During execution, the following results are generated:

{"A": 1, "B": 2, "c": 3, "d": 4, "e": 5}

The following example shows how to convert a PHP object to JSON:

The code is as follows: Copy code

<? Php
Class Emp {
Public $ name = "";
Public $ hobbies = "";
Public $ birthdate = "";
   }
$ E = new Emp ();
$ E-> name = "running in ";
$ 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 );
?>

During execution, the following results are generated:

{"Name": "coming in", "hobbies": "sports", "birthdate": "08/05/1974 12:20:03 "}

Decoding JSON in PHP (json_decode)
PHP json_decode () function is used to decode JSON in PHP. The return value of this function is decoded from json to the appropriate PHP type.

Syntax:
Mixed json_decode ($ json [, $ assoc = false [, $ depth = 512 [, $ options = 0]) parameter:
Json_string: it must be a UTF-8-encoded data-encoded string

Assoc: when this is a Boolean parameter set to TRUE, the returned object will be converted to an associated array.

Depth: it is an integer parameter that specifies the recursive depth

Options: JSON decoding of a bitmask of the integer type. JSON_BIGINT_AS_STRING is supported.

Example
The following example shows how to use PHP to decode JSON objects:

The code is as follows: Copy code

<? Php
$ Json = '{"a": 1, "B": 2, "c": 3, "d": 4, "e": 5 }';

Var_dump (json_decode ($ json ));
Var_dump (json_decode ($ json, true ));
?>

During execution, the following results are generated:

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)
}

Assume that the JSON data we obtain is as follows: (you can use curl, fsockopen, and so on)

The code is as follows: Copy code

{
"Translation": ["Hello world"],
"Query": "Hello World ",
"ErrorCode": 0,
"Web ":[
  {
"Value": ["hello world"],
"Key": "Hello World"
},
  {
"Value": ["Hello World"],
"Key": "Hello World"
  }
 ]
}

Use the json_decode function to return the array:

Array
(
[Translation] => Array
  (
[0] => Hello world
  )
[Query] => Hello world
[ErrorCode] => 0
[Web] => Array
  (
[0] => Array
    (
[Value] => Array
      (
[0] => hello world
      )
[Key] => Hello world
    )
[1] => Array
    (
[Value] => Array
      (
[0] => Hello World
      )
[Key] => Hello world
    )
  )
)

We can use the following methods in PHP to obtain the desired value:

The code is as follows: Copy code

<? Php
/*----------------------------------
$ Data ='
{
"Translation": ["Hello world"],
"Query": "Hello World ",
"ErrorCode": 0,
"Web ":[
  {
"Value": ["hello world"],
"Key": "Hello World"
},
  {
"Value": ["Hello World"],
"Key": "Hello World"
  }
 ]
}
';
-------------------------------------*/
$ Data = <STR
{
"Translation": ["Hello world"],
"Query": "Hello World ",
"ErrorCode": 0,
"Web ":[
  {
"Value": ["hello world"],
"Key": "Hello World"
},
  {
"Value": ["Hello World"],
"Key": "Hello World"
  }
 ]
}
STR;
$ Jsondata = json_decode ($ data, true );
Header ("Content-Type: text/html; charset = UTF-8 ");
// Print_r ($ jsondata );
Echo "<br/>". $ jsondata ['translation'] [0]; // Hello world
Echo "<br/>". $ jsondata ['query']; // Hello world
Echo "<br/>". $ jsondata ['web'] [0] ['value'] [0]; // hello world
Echo "<br/>". $ jsondata ['web'] [1] ['key']; // Hello, world
?>

Example, combined with database operations

The code is as follows: Copy code

<? Php
Include './include/conn. Php'; // Database link file
$ SQL _notice = mysql_query ('select * FROM gg_notice where enable = "1" limit 0, 10 ');
$ Notice = mysql_fetch_array ($ SQL _notice, MYSQL_ASSOC );
Print_r ($ notice );
?>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> tutorial provided by the first php network -- generate json format for data read from the database </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = utf-8"/>
<! -- <Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type = "text/javascript"/> </script> -->
<Script language = javascript>
</Script>
</Head>
<Body>
<Pre>
<H1> pay attention to the difference in structure between the object arrays generated by the two methods <? Php
Echo '// Assume that the following array is generated based on the data we read from the database.
$ Jarr = array ('total' => 239, 'row' => array (
Array ('code' => '001', 'name' => 'www.111cn.net ', 'add' => 'address 11 ', 'col4' => 'col4 data '),
Array ('code' => '002 ', 'name' => 'name 2', 'addr' => 'address 12 ', 'col4' => 'col4 data '),
                                     )
);
// Method 1:
$ Jobj = new stdclass (); // instantiate stdclass, which is an empty class built in php and can be used to transmit data. Because the data after json_decode is stored as an object array,
// Therefore, we need to store the data in the object during generation.
Foreach ($ jarr as $ key => $ value ){
$ Jobj-> $ key = $ value;
}
Print_r ($ jobj); // Print the object after passing the attribute
Echo 'use $ jobj-> row [0] ['code'] to output array elements :'. $ jobj-> row [0] ['code']. '<br> ';
Echo 'encoded json string: '. json_encode ($ jobj).' <br> '; // Print the encoded json string


Echo '// Method 2:
Echo 'Echo 'encoded json string :';
Echo $ str = json_encode ($ jarr); // Encode the array in json format.
Echo '<br> ';
$ Arr = json_decode ($ str); // perform json decoding.
Print_r ($ arr); // Print the decoded array. The data is stored in the object array.
Echo 'use $ arr-> row [0]-> code output array element:'. $ arr-> row [0]-> code;

?>

</Body>
</Html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.