PHP 中 json_encode() 只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。
$arr = array(
‘0’=>’a’,’1’=>’b’,’2’=>’c’,’3’=>’d’
);
echo json_encode($arr);
结果是:
[“a”,”b”,”c”,”d”]
而不是
{“0”:”a”,”1”:”b”,”2”:”c”,”3”:”d”}
强制转成对象
$arr = array(
‘0’=>’a’,’1’=>’b’,’2’=>’c’,’3’=>’d’
);
echo json_encode((object)$arr);
输出结果:
{“0”:”a”,”1”:”b”,”2”:”c”,”3”:”d”}
json_encode()序列化一个对象时,会先提取(get_object_vars)对象的公有(public、static)属性合并为一个数组,再进行序列化。private、protected属性以及类方法都将被丢弃。
但是如果继承自arrayObject 所有属性会被丢弃,除非继承JsonSerializable 并且实现jsonSerialize方法
<?php
/**
class B extends \ArrayObject {
public $a;
public $_b;
private $c;
static $d;
protected $e;
public function __construct($a, $b){
$this->a = $a;
$this->_b = $b;
$this->c=4;
$this->d=5;
$this->e=6;
}
public function sum(){
return $this->a + $this->b;
}
public function jsonSerialize(){
$aRet=[];
$aRet[‘f’]=7;
return $aRet;
}
}
$obj = new B(1,2);
echo json_encode($obj);
class C extends \ArrayObject implements JsonSerializable {
public $a;
public $_b;
private $c;
static $d;
protected $e;
public function __construct($a, $b){
$this->a = $a;
$this->_b = $b;
$this->c=4;
$this->d=5;
$this->e=6;
}
public function sum(){
return $this->a + $this->b;
}
public function jsonSerialize()
{
parent::serialize(); // TODO: Change the autogenerated stub
$aRet=[];
foreach ($this as $k=>$v){
$aRet[$k]=$v;//走不进去
}
$this['g']=8; //仅仅可以输出这个
$aRet=$this->getArrayCopy();
$aRet['f']=7;
return $aRet;
} } $obj = new C(1,2); echo json_encode($obj); //$ php json.php //{"a":1,"_b":2,"d":5}{}{"g":8,"f":7}
https://segmentfault.com/a/1190000021314708
https://blog.csdn.net/fdipzone/article/details/79771348