php中JSON的使用與轉(zhuǎn)換
Jun 06, 2016 pm 08:14 PM這篇文章主要介紹了php中JSON的使用與轉(zhuǎn)換,講解的十分細(xì)致全面,是篇非常不錯的文章,需要的朋友可以參考下
在之前我寫過php返回json數(shù)據(jù)簡單實(shí)例,剛剛上網(wǎng),突然發(fā)現(xiàn)一篇文章,也是介紹json的,還挺詳細(xì),值得參考。內(nèi)容如下
從5.2版本開始,PHP原生提供json_encode()和json_decode()函數(shù),前者用于編碼,后者用于解碼。
一、json_encode()
復(fù)制代碼 代碼如下:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
輸出
復(fù)制代碼 代碼如下:
{"a":1,"b":2,"c":3,"d":4,"e":5}
再看一個對象轉(zhuǎn)換的例子:
復(fù)制代碼 代碼如下:
$obj->body?????????? = 'another post';
$obj->id???????????? = 21;
$obj->approved?????? = true;
$obj->favorite_count = 1;
$obj->status???????? = NULL;
echo json_encode($obj);
?輸出
復(fù)制代碼 代碼如下:
{
"body":"another post",
"id":21,
"approved":true,
"favorite_count":1,
"status":null
}
?由于json只接受utf-8編碼的字符,所以json_encode()的參數(shù)必須是utf-8編碼,否則會得到空字符或者null。當(dāng)中文使用GB2312編碼,或者外文使用ISO-8859-1編碼的時候,這一點(diǎn)要特別注意。
二、索引數(shù)組和關(guān)聯(lián)數(shù)組
PHP支持兩種數(shù)組,一種是只保存"值"(value)的索引數(shù)組(indexed array),另一種是保存"名值對"(name/value)的關(guān)聯(lián)數(shù)組(associative array)。
由于javascript不支持關(guān)聯(lián)數(shù)組,所以json_encode()只將索引數(shù)組(indexed array)轉(zhuǎn)為數(shù)組格式,而將關(guān)聯(lián)數(shù)組(associative array)轉(zhuǎn)為對象格式。
比如,現(xiàn)在有一個索引數(shù)組
復(fù)制代碼 代碼如下:
$arr = Array('one', 'two', 'three');
echo json_encode($arr);
?輸出
復(fù)制代碼 代碼如下:
["one","two","three"]
?如果將它改為關(guān)聯(lián)數(shù)組:
復(fù)制代碼 代碼如下:
$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
?輸出變?yōu)?/p>
復(fù)制代碼 代碼如下:
{"1":"one","2":"two","3":"three"}
?注意,數(shù)據(jù)格式從"[]"(數(shù)組)變成了"{}"(對象)。
如果你需要將"索引數(shù)組"強(qiáng)制轉(zhuǎn)化成"對象",可以這樣寫
復(fù)制代碼 代碼如下:
json_encode( (object)$arr );
?或者
復(fù)制代碼 代碼如下:
json_encode ( $arr, JSON_FORCE_OBJECT );
?三、類(class)的轉(zhuǎn)換
下面是一個PHP的類:
復(fù)制代碼 代碼如下:
class Foo {
const???? ERROR_CODE = '404';
public??? $public_ex = 'this is public';
private?? $private_ex = 'this is private!';
protected $protected_ex = 'this should be protected';
public function getErrorCode() {
return self::ERROR_CODE;
}
}
?現(xiàn)在,對這個類的實(shí)例進(jìn)行json轉(zhuǎn)換:
復(fù)制代碼 代碼如下:
$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
?輸出結(jié)果是
復(fù)制代碼 代碼如下:
{"public_ex":"this is public"}
?可以看到,除了公開變量(public),其他東西(常量、私有變量、方法等等)都遺失了。
四、json_decode()
該函數(shù)用于將json文本轉(zhuǎn)換為相應(yīng)的PHP數(shù)據(jù)結(jié)構(gòu)。下面是一個例子:
復(fù)制代碼 代碼如下:
$json = '{"foo": 12345}';
$obj = json_decode($json);
print $obj->{'foo'}; // 12345
?通常情況下,json_decode()總是返回一個PHP對象,而不是數(shù)組。比如:
復(fù)制代碼 代碼如下:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?結(jié)果就是生成一個PHP對象:
復(fù)制代碼 代碼如下:
object(stdClass)#1 (5) {
?
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
?
}
?如果想要強(qiáng)制生成PHP關(guān)聯(lián)數(shù)組,json_decode()需要加一個參數(shù)true:
復(fù)制代碼 代碼如下:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?結(jié)果就生成了一個關(guān)聯(lián)數(shù)組:
復(fù)制代碼 代碼如下:
array(5) {
? ["a"] => int(1)
? ["b"] => int(2)
? ["c"] => int(3)
? ["d"] => int(4)
? ["e"] => int(5)
}
五、json_decode()的常見錯誤
下面三種json寫法都是錯的,你能看出錯在哪里嗎?
復(fù)制代碼 代碼如下:
$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';
?對這三個字符串執(zhí)行json_decode()都將返回null,并且報錯。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w
