The conversion between PHP objects (objects) and arrays (array) is used a lot in our development. For this problem, we have compiled some examples today, as shown below.
Arrays are the soul of PHP and are very powerful, but sometimes object-oriented programming is also very convenient. Switching between arrays and objects is also common:
Example 1
代码如下 | 复制代码 |
/** return (object)$arr; /** return $obj; |
The code is as follows | Copy code | ||||
/**
}<script>ec(2);</script> /** * Object to array * * @param object $obj object * @return array */ function object_to_array($obj) { $obj = (array)$obj; foreach ($obj as $k => $v) { if (gettype($v) == 'resource') { Return; } if (gettype($v) == 'object' || gettype($v) == 'array') { $obj[$k] = (array)object_to_array($v); } } return $obj; } |
The code is as follows | Copy code |
<🎜>class Test{ Public $a; Public $b; Public function __construct($a) { $this->a = $a; } } //Convert object to array, use get_object_vars to return an array composed of object attributes function objectToArray($obj){ $arr = is_object($obj) ? get_object_vars($obj) : $obj; If(is_array($arr)){ return array_map(__FUNCTION__, $arr); }else{ return $arr; } } //Convert array to object function arrayToObject($arr){ If(is_array($arr)){ return (object) array_map(__FUNCTION__, $arr); }else{ return $arr; } } $test = new Test('test1'); $test->b = new Test('test2'); print_r($test); $array = objectToArray($test); print_r($array); $object = arrayToObject($array); print_r($object); |