Home php教程 php手册 PHP6 先修班 JSON实例代码

PHP6 先修班 JSON实例代码

Jun 13, 2016 pm 12:27 PM
javascript json language programming code Example

它是基於JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一個子集
JSON 主要利用了成對的 {} 來包住各個object(物件),用成對的 [] 來包各個array(陣列),
用成對的 "" 來包住各字串,用逗號來區隔各變數而資料型態有 string, number, array, object

下面簡單的JSON格式,敘述了一個 object json 擁有一個成員變數,這個成員變數中有含有三個物件

复制内容到剪贴板代码:
var json = {
'query' : [
{'id':'1','type':'a','title':'PHP 5.2.0 的新功能 JSON decoder & encoder'},
{'id':'2','type':'b','title':'JSON 全稱 JavaScript Object Notation'},
{'array': ['A', 'B','C', 'D', 'E']}
]
};
如此,我們可以獲得一個叫做 json 的Object,而這個json Object中包含一個獨立的成員 query
而query包含一個Array ,這個Array中又含了三個Object,前面二個Object含有三個成員
id,type,title,而最後一個Object array 包含一個陣列,如此解釋還明白吧?

但是要怎麼用呢?
很簡單
alert('I have ' +json.query.length + ' object.');
//alert I have 3 object.
alert('type='+json.query[1].type+'\r\ntitle'+json.query[1].title);
//alert type=b title=JSON 全稱 JavaScript Object Notation
alert('陣列索引3='+json.query[2].array[3]);
//alert 陣列索引3=D

這樣操作資料時更簡便,不需要和複雜的DOM打交道,所需要的資料可以很輕鬆的取得
例如上面的例子 json.query[ i ].title 如此就可以取得第i筆的title內含的值
PHP的發展是很迅速,當程式界對JSON還一知半解時或者全然不知何為JSON時
PHP已經在最新的版本5.2.0中納入核心,並且預設狀態是啟用,相較於其他的Script語言
PHP可謂一馬當先,在5.2.0版本中為JSON實作了兩個函數 json_decode() 和 json_encode()
前者是將JSON格式的字串還原成PHP原生的陣列
後者則是將PHP原生陣列編譯成JSON格式的字串
不過,由於Javascript支援Unicode,如果在存取資料庫時使用非Ascii的字元,如中、日、韓
需要將字元編碼轉換成UTF8,不然經過json_encode()後的字串會是亂碼
========================================================
經過上一篇簡單介紹JOSN後
本篇就來實作如何使用JOSN
下面範例使用需要使用MySQL4.1以上版本
編碼全程採用utf8
承接上一篇的資料格式,表中共有三個欄位id,type,title
資料表規格如下
复制内容到剪贴板代码:
CREATE TABLE `news` (
`id` int(10) unsigned NOT NULL auto_increment,
`type` varchar(255) NOT NULL default '',
`title` varchar(64) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
复制内容到剪贴板代码:
//建立連線
$conn = mysqli_connect("localhost", 'root', '')or die('連不上資料庫');
//選擇資料庫
mysqli_select_db($conn,'mydata') or die('不能選資料庫');
//設定連線編碼規則,不懂上google找
mysqli_query($conn,'SET NAMES 'utf8'');
//取出資料
$results = mysqli_query($conn,'SELECT id,type,title FROM news');
//Josn字串
$json = '';
//因為是範例,所以自行控制迴圈
$i=0;
while($row = mysqli_fetch_assoc($results))
{
$i++;
$json .= json_encode($row);
//資料表中只放三筆資料,所以在第三筆時不需要在尾巴加上 ",",記得,最後一筆資料不用加上","
if ($i{
$json .= ",";
}

}
//將資料包進陣列中
$json = '{"query":[ '.$json.']}';?>



Json範例








還原Json

//將字串解碼
$s_JSON_Decoded = json_decode($json,true);
//取回資料
foreach ($s_JSON_Decoded as $row)
{
foreach ($row as $rowa)
{
echo $rowa['title']."
";
}

}
?>


經過簡單的演練後
相信大家對JSON這玩意有更深一層的瞭解
當然JSON的應用不只是範例中那麼簡單
有興趣一起研究吧
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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

System76 tips Fedora Cosmic spin for 2025 release with Fedora 42 System76 tips Fedora Cosmic spin for 2025 release with Fedora 42 Aug 01, 2024 pm 09:54 PM

System76 has made waves recently with its Cosmic desktop environment, which is slated to launch with the next major alpha build of Pop!_OS on August 8. However, a recent post on X by System76 CEO, Carl Richell, has tipped that the Cosmic DE developer

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension ".a" have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run ".a" files. This article will introduce how to comprehensively install and configure the Linux ".a" file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux ".a" file. What is L

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Create Agent in one sentence! Robin Li: The era is coming when everyone is a developer Apr 17, 2024 pm 02:28 PM

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself

The relationship between the number of Oracle instances and database performance The relationship between the number of Oracle instances and database performance Mar 08, 2024 am 09:27 AM

The relationship between the number of Oracle instances and database performance Oracle database is one of the well-known relational database management systems in the industry and is widely used in enterprise-level data storage and management. In Oracle database, instance is a very important concept. Instance refers to the running environment of Oracle database in memory. Each instance has an independent memory structure and background process, which is used to process user requests and manage database operations. The number of instances has an important impact on the performance and stability of Oracle database.

See all articles