php中如何把对象转化为json呢?
(1)对于普通的php对象
- //convert object to array
- function object_to_array($obj){
- if(is_array($obj)){
- return $obj;
- }
- $_arr = is_object($obj)? get_object_vars($obj) :$obj;
- foreach ($_arr as $key => $val){
- $val=(is_array($val)) || is_object($val) ? object_to_array($val) :$val;
- $arr[$key] = $val;
- }
- return $arr;
- }
- /**
- * 把对象转化为json
- */
- function object_to_json($obj){
- $arr2=object_to_array($obj);//先把对象转化为数组
- return json_encode($arr2);
- }
(2)yii框架中的对象
例如user是yii对象的话,先通过user.attributes获取成员变量,然后在转化为json