本文实例讲述了Zend Framework处理Json数据的方法。,具体如下:
JSON分隔符及意义
{} 用于实现对象的包含,对象都包含在大括号中
, 逗号用于分隔对象的不同属性,或者数组的元素
[] 用于存放数组,数组将存放在中括号中
: 用于表示键/值对的值,冒号前为键,冒号后为该键的值
JSON示例
{
"addressbook":{
"name":"Mary Lebow",
"address":{
"street":"5 Main Street",
"city":"San Diego,CA",
"zip":91912
},
"phoneNumbers":[
"619 332-3452",
"664 223-4667"
]
}
}
使用JSON
语法:$json = Zend_Json::encode($phpNative);
说明:其中,参数$phpNative为PHP常见的数据类型,可以是数组、对象或者其他类型的数据。
函数返回值$json为符合JSON格式的一个字符串。
示例:
<?php
require_once("Zend/Json.php");
$temp = array(
"a"=>0,
"b"=>1,
"c"=>array(
"c-1"=>21,
"c-2"=>22,
"c-3"=>23,
),
"d"=>3
);
$json = Zend_Json::encode($temp);
echo "临时数组内容为:";
echo "<pre>";
print_r($temp);
echo "</pre>";
echo "转换为JSON格式内容为:";
echo "<pre>";
print_r($json);
echo "</pre>";
结果为:
临时数组内容为:
Array
(
[a] => 0
[b] => 1
[c] => Array
(
[c-1] => 21
[c-2] => 22
[c-3] => 23
)
[d] => 3
)
转换为JSON格式内容为:
{"a":0,"b":1,"c":{"c-1":21,"c-2":22,"c-3":23},"d":3}
将JSON解码为普通数据
语法:$phpNative = Zend_Json::decode($json);
示例:
<?php
require_once("Zend/Json.php");
$json = "{
"addressbook":{
"name":"zhangsan",
"address":{
"street":"Chang an jie",
"city":"BeiJing",
"zip":100001
},
"phoneNumbers":[
"010-12345678",
"010-11111111"
]
}
}";
echo "解码前为:";
echo "<pre>";
print_r($json);
echo "</pre>";
$native = Zend_Json::decode($json);
echo "解码后为:";
echo "<pre>";
print_r($native);
echo "</pre>";
输出结果为:
解码前为:
{
"addressbook":{
"name":"zhangsan",
"address":{
"street":"Chang an jie",
"city":"BeiJing",
"zip":100001
},
"phoneNumbers":[
"010-12345678",
"010-11111111"
]
}
}
解码后为:
Array
(
[addressbook] => Array
(
[name] => zhangsan
[address] => Array
(
[street] => Chang an jie
[city] => BeiJing
[zip] => 100001
)
[phoneNumbers] => Array
(
[0] => 010-12345678
[1] => 010-11111111
)
)
)







