您的位置:首页 > 产品设计 > UI/UE

***php解析JSON二维数组字符串(json_decode函数第二个参数True和False的区别)

2015-03-05 15:25 711 查看
客户端的请求体中的数据:[{"msg_id": 1, "msg_status": "HAS_READ" }, { "msg_id": 2, "msg_status": "HAS_READ" }] 是一个二维数组字符串

$json_data = json_decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
其实用这一句即可实现JSON二维数组字符串转PHP的二维数组变量,不用自己动态构造二维数组
该函数的第二个参数很重要:不加true会以PHP对象输出, 加true输出PHP数组

   /**
* 根据上传的消息ID集合来批量更新消息的状态
*/
public function update_status_batch()
{
//需要更新的数据
/* $data = array(
array(
'msg_id' => 1 ,
'msg_status' => 'HAS_READ'
),
array(
'msg_id' => 2 ,
'msg_status' => 'HAS_READ'
)
);*///返回值默认是JSON对象,当第二个可选参数是TRUE的时候,则返回的是数组;如果是二维数组的JSON字符串,这里也会转换为二维数组的PHP变量
$json_data = json_decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
/* //元素个数
//$item_num = count($json_data);
//定义二维数组
$array = array();
foreach($json_data as $item){
$array_unit = array(
'msg_id' => $item->msg_id,
'msg_status' => $item->msg_status
);
//往二维数组追加元素
array_push($array,$array_unit);
}*///更新,返回值是更新所影响的记录条数
$result = $this->m_user_msg->update_batch($json_data, 'msg_id');
if(!empty($result)){
//如果不为空,就返回成功
$return_data['code']= '100';
$return_data['msg']= '处理成功';
//需要进行字符串转数字处理
$return_data['data']= $result;}else{
$return_data['code']= '400';
$return_data['msg']= '处理失败';
$return_data['data']= $json_data;
}//设置以JSON返回给请求方
header('Content-Type:application/json; charset=utf-8');
//转换为JSON字符串
echo stripslashes(json_encode($return_data, JSON_UNESCAPED_UNICODE)) ;}
-------------------------------------------------------------------------------------------------------json_decode函数第二个参数True和False的区别默认值:false,返回object对象Array
(
[0] => stdClass Object
(
[name] => C51790CC-EDEF-4DF7-9CC7-FE8F4DC8138B&ext=JPG
[width] => 200
[height] => 149
)[1] => stdClass Object
(
[name] => 4E6A33AD-D9AE-47CD-9711-E95D9184FBC2&ext=JPG.jpg
[width] => 160
[height] => 160
))为true的情况,返回数组array:Array
(
[0] => Array
(
[name] => C51790CC-EDEF-4DF7-9CC7-FE8F4DC8138B&ext=JPG
[width] => 200
[height] => 149
)[1] => Array
(
[name] => 4E6A33AD-D9AE-47CD-9711-E95D9184FBC2&ext=JPG.jpg
[width] => 160
[height] => 160
))官方解释:

json_decode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)json_decode — 对 JSON 格式的字符串进行编码

说明

mixed json_decode ( string
$json
[, bool
$assoc
= false [, int
$depth
= 512 [, int
$options
= 0 ]]] )
接受一个 JSON 格式的字符串并且把它转换为 PHP 变量

参数

json

待解码的
json
string 格式的字符串。This function only works with UTF-8 encoded data.
assoc

当该参数为
TRUE
时,将返回 array 而非 object
depth

User specified recursion depth.
options

Bitmask of JSON decode options. Currently only
JSON_BIGINT_AS_STRING
is supported (default is to cast large integers as floats)

返回值

Returns the value encoded in
json
in appropriate PHP type. Values true, false and null (case-insensitive) are returned as
TRUE
,
FALSE
and
NULL
respectively.
NULL
is returned if the
json
cannot be decoded or if the encoded data is deeper than the recursion limit.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: