php object array 相互转换

Table of Contents

代码

#!/usr/bin/php
<?php
//object to array
$obj = new stdClass();
$obj->name = "josephzeng";
$obj->age = 30;
var_dump($obj);

//
$obj_to_array = (array) $obj;
var_dump($obj_to_array);

//
$obj_to_array = json_decode(json_encode($obj), true);
var_dump($obj_to_array);


//array to object
$array_to_obj = (object) $obj_to_array;
var_dump($array_to_obj);

输出

➜  php php array_object.php
object(stdClass)#1 (2) {
  ["name"]=>
  string(10) "josephzeng"
  ["age"]=>
  int(30)
}
array(2) {
  ["name"]=>
  string(10) "josephzeng"
  ["age"]=>
  int(30)
}
array(2) {
  ["name"]=>
  string(10) "josephzeng"
  ["age"]=>
  int(30)
}
object(stdClass)#2 (2) {
  ["name"]=>
  string(10) "josephzeng"
  ["age"]=>
  int(30)
}

Author: josephzeng

Last Updated 2016-04-11. Created by Emacs 24.5.1 (Org mode 8.2.10)

Validate