龙空技术网

PHP与json通讯

寒笛过霜天 108

前言:

而今咱们对“phpinarr”大体比较注意,大家都需要知道一些“phpinarr”的相关知识。那么小编也在网上搜集了一些有关“phpinarr””的相关文章,希望我们能喜欢,看官们快快来学习一下吧!

在PHP语言中使用json和将json还原成数组(对象)

从5.2版本开始, PHP原生提供json_encode()和json_decode()函数, 前者用于编码, 后者用于解码。

一 json_encode()

<?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}<?php//定义一个对象$std = new StdClass();$std->name = "xiaomei";$std->age = "22";$std->email = 'xm@itcast.cn';echo json_encode($std);?>

对象生成json信息(只考虑"属性")

class Person{public $name = "tom";public $height = 175;public function run(){echo "I am running";}}$per = new Person();echo json_encode($per);//{"name":"tom","height":175}

由于json只接受utf-8编码的字符, 所以json_encode()的参数必须是utf-8编码, 否则会得到空字符或者null。

当中文使用GB2312编码, 或者外文使用ISO-8859-1编码的时候, 这一点要特别注意, 需要使用iconv()函数转码。

二 索引数组和关联数组

PHP支持两种数组, 一种是只保存"值"(value)的索引数组(indexed array), 另一种是保存"名值对"(name/value)的关联数组(associative array)。

由于javascript不支持关联数组, 所以json_encode()只将索引数组(indexed array)转为数组格式, 而将关联数组(associative array)转为对象格式。

索引数组---->js数组

$color = array('red','blue','green');echo json_encode($color),"<br />"; //["red","blue","green"]

关联数组---->js的json对象

$animal = array('north'=>'wolf','helan'=>'pig','germany'=>'dog');echo json_encode($animal),"<br />"; //{"north":"wolf","helan":"pig","germany":"dog"}

索引关联混合数组---->js的json对象

$animal2 = array('north'=>'wolf','monkey','helan'=>'pig','germany'=>'dog');echo json_encode($animal2),"<br />"; //{"north":"wolf","0":"monkey","helan":"pig","germany":"dog"}

如果你需要将"索引数组"强制转化成"对象", 可以这样写

json_encode( $arr, JSON_FORCE_OBJECT ); PHP5.3.0以上版本支持$color = array('red','blue','green');echo json_encode($color,JSON_FORCE_OBJECT); //{"0":"red","1":"blue","2":"green"}

三 类(class)的转换

下面是一个PHP的类:

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;  }}

现在, 对这个类的实例进行json转换:

$foo = new Foo;$foo_json = json_encode($foo);echo $foo_json;

输出结果是: {"public_ex":"this is public"}

可以看到, 除了公开变量(public), 其他东西(常量、私有变量、方法等等)都遗失了。

四 json_decode()

json_decode()对JSON格式的字符串进行编码, 该函数用于将json文本转换为相应的PHP数据结构。

mixed json_decode ( string $json [, bool $assoc = false] )

json 待解码的json为 string 格式的字符串, 这个函数仅支持utf-8字符集。

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

true: array

false: object, 默认值

$animal = array("north"=>"wolf","helan"=>"pig","germany"=>"dog");$in_animal = json_encode($animal);$json_decode = json_decode($in_animal);echo $json_decode->north; //wolf 也可写成$json_decode->{'north'};echo $json_decode->{'helan'}; //pigecho $json_decode->{"helan"}; //pig

通常情况下, json_decode()总是返回一个PHP对象, 而不是数组。比如:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';var_dump(json_decode($json));

结果就是生成一个PHP对象:

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)

}

实例:索引数组的编码与反编码

$color = array('red','blue','green');$jn_color = json_encode($color); //["red","blue","green"]var_dump(json_decode($jn_color,true));//array(3) { [0]=> string(3) "red" [1]=> string(4) "blue" [2]=> string(5) "green" }

实例:多维数组解析成对象

<?php$arr = array(array("id"=>"1","username"=>"孙悟空","sex"=>"男", "nickname"=>"美猴王"),array("id"=>"2","username"=>"唐僧","sex"=>"男", "nickname"=>"唐玄奘"),array("id"=>"3","username"=>"猪八戒","sex"=>"男", "nickname"=>"猪刚鬣"),array("id"=>"4","username"=>"沙僧","sex"=>"男", "nickname"=>"卷帘大将"),);$json_arr = json_encode($arr);echo $json_arr;$json_decode = json_decode($json_arr);echo "<pre>";print_r($json_decode);echo "</pre>";

输出结果:

[{"id":"1","username":"\u5b59\u609f\u7a7a","sex":"\u7537","nickname":"\u7f8e\u7334\u738b"},{"id":"2","username":"\u5510\u50e7","sex":"\u7537","nickname":"\u5510\u7384\u5958"},{"id":"3","username":"\u732a\u516b\u6212","sex":"\u7537","nickname":"\u732a\u521a\u9b23"},{"id":"4","username":"\u6c99\u50e7","sex":"\u7537","nickname":"\u5377\u5e18\u5927\u5c06"}]Array([0] => stdClass Object([id] => 1[username] => 孙悟空[sex] => 男[nickname] => 美猴王)[1] => stdClass Object([id] => 2[username] => 唐僧[sex] => 男[nickname] => 唐玄奘)[2] => stdClass Object([id] => 3[username] => 猪八戒[sex] => 男[nickname] => 猪刚鬣)[3] => stdClass Object([id] => 4[username] => 沙僧[sex] => 男[nickname] => 卷帘大将))

五 json_decode()的常见错误

下面二种json写法都是错的, 你能看出错在哪里吗?

$bad_json = "{'bar': 'baz'}";

$bad_json = '{"bar": "baz",}';

对这二个json字符串执行json_decode()都将返回null, 并且报错。

第一个的错误是, json的分隔符(delimiter)内只允许使用双引号, 不能使用单引号, 分隔符外使用单引号。

第二个的错误是, 最后一个值之后不能添加逗号。

正确格式:$bad_json = '{"bar": "baz"}';

结果: PHP创建json对象时, 最外面只能使用单引号

另外,json只能用来表示对象(object)和数组(array), 如果对一个字符串或数值使用json_decode(), 将会返回null。

var_dump(json_decode("Hello World")); //null

六 如何将数组解析成[{},{},{}]

<?php$arr1 = array("one"=>1, "two"=>2);echo json_encode($arr1); //{"one":1, "two":2}$arr = array(array("one"=>1), array("two"=>2));echo json_encode($arr); //[{"one":1},{"two":2}]?>

七 生成一个json空数组[]

$result=array();$json_str = json_encode(array('status'=>0,'msg'=>'添加失败','result'=>$result));echo $json_str;exit();

输出结果: {"status":0,"msg":"\u6dfb\u52a0\u5931\u8d25","result":[]}

八 生成一个json空对象{}

第一种方法

$result=array();$json_str = json_encode(array('status'=>0,'msg'=>'数据写入失败','result'=>$result), JSON_FORCE_OBJECT);echo $json_str;exit();

输出结果:

{"status":0,"msg":"\u6570\u636e\u5199\u5165\u5931\u8d25","result":{}}

第二种方法:

$result=(object)array();$json_str = json_encode(array('status'=>0,'msg'=>'添加失败','result'=>$result));echo $json_str;exit();

输出结果:

{"status":0,"msg":"\u6dfb\u52a0\u5931\u8d25","result":{}}

九 将关联数组解析成[{},{}]

<?php$result=array("荆州"=>2, "武汉"=>3, "深圳"=>6);$arr = array();foreach($result as $key=>$value){$arr[$key] = array($key=>$value);}echo urlencode(json_encode(array_values($arr)));?>

输出结果:

[{"\u8346\u5dde":2},{"\u6b66\u6c49":3},{"\u6df1\u5733":6}]

注意:

关联数组中键名为"0"、"1"的连续性字符串解析问题

<?php$data['Property'] = array("0"=>"个人用车", "1"=>"企业用车", "2"=>"机关团队用车"); //车辆所属性质 父类 键值为 "0" "1" "2" "3" json_encode 将解析为[{},{},{}] 并去掉键名$data['carProperty'] = array("0"=>array("1"=>"家庭自用汽车", "2"=>"出租租凭营业客车", "3"=>"城市公交营业客车", "4"=>"公路客运营业客车", "5"=>"旅游营业客车", "6"=>"营业货车", "12"=>"非营业货车", "15"=>"营业特种车", "16"=>"非营业特种车"),"1"=>array("2"=>"出租租凭营业客车", "3"=>"城市公交营业客车", "4"=>"公路客运营业客车", "5"=>"旅游营业客车", "6"=>"营业货车", "10"=>"企业非营业客车", "11"=>"机关非营业客车", "12"=>"非营业货车", "15"=>"营业特种车", "16"=>"非营业特种车"),"2"=>array("2"=>"出租租凭营业客车", "3"=>"城市公交营业客车", "4"=>"公路客运营业客车", "5"=>"旅游营业客车", "6"=>"营业货车", "10"=>"企业非营业客车", "11"=>"机关非营业客车", "12"=>"非营业货车", "15"=>"营业特种车", "16"=>"非营业特种车")); //车辆使用性质 父类下的子类 键值为 "0" "1" "2" "3" json_encode 将解析为[{},{},{}] 并去掉键名$data['isTruck'] = array(6, 12, 15, 16); //carProperty下 哪些属于货车$json_str = json_encode(array('status'=>1,'msg'=>'获取所属车辆性质数据成功','result'=>$data));echo $json_str;/*{"status":1,"msg":"获取所属车辆性质数据成功","result": {"Property":["个人用车","企业用车","机关团队用车"],"carProperty":[{"1":"家庭自用汽车","2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"},{"2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","10":"企业非营业客车","11":"机关非营业客车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"},{"2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","10":"企业非营业客车","11":"机关非营业客车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"}],"isTruck":[6,12,15,16]}}*///解决方法echo "<br>";$json_str = json_encode(array('status'=>1,'msg'=>'获取所属车辆性质数据成功','result'=>$data),JSON_FORCE_OBJECT); //JSON_FORCE_OBJECT 强制解析成{{},{},{}}, 而且并未去掉键名echo $json_str;/*{"status":1,"msg":"获取所属车辆性质数据成功","result":{"Property":{"0":"个人用车","1":"企业用车","2":"机关团队用车"},"carProperty":{"0":{"1":"家庭自用汽车","2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"},"1":{"2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","10":"企业非营业客车","11":"机关非营业客车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"},"2":{"2":"出租租凭营业客车","3":"城市公交营业客车","4":"公路客运营业客车","5":"旅游营业客车","6":"营业货车","10":"企业非营业客车","11":"机关非营业客车","12":"非营业货车","15":"营业特种车","16":"非营业特种车"}},"isTruck":{"0":6,"1":12,"2":15,"3":16}}}*/

实例:

<?php$res = '[{"prvId":"20054419"},{"prvId":"20434419"},{"prvId":"20214419"},{"prvId":"20264419"}]'; //外边不能为双信号$arr = json_decode($res, true);print_r($arr);?>显示结果:Array([0] => Array([prvId] => 20054419)[1] => Array([prvId] => 20434419)[2] => Array([prvId] => 20214419)[3] => Array([prvId] => 20264419))实例:<?php$json = '{"taskId": "1840391","prvId": "20074419","prvName": "平安财险","code": "0","msg": "系统网路开小差了","channelId": "qd_newssj","channelUserId": "110","taskState": "20","taskStateDescription": "报价失败","carInfo": {"carLicenseNo": "粤AP3322","carProperty": "1"},"carOwner": {"name": "测试赵","mobile": "18923328712"},"insureInfo": {"efcInsureInfo": {"startDate": "2016-10-29","endDate": "2017-10-28","amount": "1.00","premium": "0.00"},"taxInsureInfo": {"lateFee": "0.00","taxFee": "0.00"},"bizInsureInfo": {"startDate": "2016-10-29","endDate": "2017-10-28","nfcPremium": "0.00","riskKinds": [{"riskCode": "VehicleDemageIns","riskName": "机动车损失保险","amount": "86800.00","notDeductible": "Y","ncfPremium": "0.0000"},{"riskCode": "ThirdPartyIns","riskName": "机动车第三者责任保险","amount": "300000.00","notDeductible": "Y","ncfPremium": "0.0000"},{"riskCode": "DriverIns","riskName": "司机责任险","amount": "50000.00","notDeductible": "Y","ncfPremium": "0.0000"},{"riskCode": "GlassIns","riskName": "玻璃单独破碎险","amount": "1.00","notDeductible": "N"},{"riskCode": "PassengerIns","riskName": "乘客责任险","amount": "50000.00","notDeductible": "Y","ncfPremium": "0.0000"}]}}}';echo "<pre>";print_r(json_decode($json, true));echo "</pre>";?>

输出结果:

Array([taskId] => 1840391[prvId] => 20074419[prvName] => 平安财险[code] => 0[msg] => 系统网路开小差了[channelId] => qd_newssj[channelUserId] => 110[taskState] => 20[taskStateDescription] => 报价失败[carInfo] => Array([carLicenseNo] => 粤AP3322[carProperty] => 1)[carOwner] => Array([name] => 测试赵[mobile] => 18923328712)[insureInfo] => Array([efcInsureInfo] => Array([startDate] => 2016-10-29[endDate] => 2017-10-28[amount] => 1.00[premium] => 0.00)[taxInsureInfo] => Array([lateFee] => 0.00[taxFee] => 0.00)[bizInsureInfo] => Array([startDate] => 2016-10-29[endDate] => 2017-10-28[nfcPremium] => 0.00[riskKinds] => Array([0] => Array([riskCode] => VehicleDemageIns[riskName] => 机动车损失保险[amount] => 86800.00[notDeductible] => Y[ncfPremium] => 0.0000)[1] => Array([riskCode] => ThirdPartyIns[riskName] => 机动车第三者责任保险[amount] => 300000.00[notDeductible] => Y[ncfPremium] => 0.0000)[2] => Array([riskCode] => DriverIns[riskName] => 司机责任险[amount] => 50000.00[notDeductible] => Y[ncfPremium] => 0.0000)[3] => Array([riskCode] => GlassIns[riskName] => 玻璃单独破碎险[amount] => 1.00[notDeductible] => N)[4] => Array([riskCode] => PassengerIns[riskName] => 乘客责任险[amount] => 50000.00[notDeductible] => Y[ncfPremium] => 0.0000)))))

标签: #phpinarr #php5510安装 #php通讯