Php encode decode区别,encode()和decode()区别

Php (4) 2024-04-19 10:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说Php encode decode区别,encode()和decode()区别,希望能够帮助你!!!。

一、json_encode()

将PHP的数据结构转换成JOSN

代码1<?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);?>

结果{"a":1,"b":2,"c":3,"d":4,"e":5}

代码2$obj->body = 'another post';

$obj->id = 21;

$obj->approved = true;

$obj->favorite_count = 1;

$obj->status = NULL;

echo json_encode($obj);

结果{

"body":"another post",

"id":21,

"approved":true,

"favorite_count":1,

"status":null

}

二、json_decode()

将json文本转换为相应的PHP数据结构

代码1$json = '{"foo": 12345}';

$obj = json_decode($json);

print $obj->{'foo'}; // 12345

代码2$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));

结果object(stdClass)#1 (5) {

["a"] => int(1)

["b"] => int(2)

["c"] => int(3)

["d"] => int(4)

["e"] => int(5)

}

如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:

代码$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json,true));

结果array(5) {   ["a"] => int(1)

["b"] => int(2)

["c"] => int(3)

["d"] => int(4)

["e"] => int(5)}

链接:https://www.jianshu.com/p/c5bb7b28c94b

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

发表回复