php对象和数组的相互转换,Array2object()、Object2array()
1 function array2object($array) { 2 3 if (is_array($array)) { 4 $obj = new StdClass(); 5 6 foreach ($array as $key => $val){ 7 $obj->$key = $val; 8 } 9 } 10 else { $obj = $array; } 11 12 return $obj; 13 } 14 15 function object2array($object) { 16 if (is_object($object)) { 17 foreach ($object as $key => $value) { 18 $array[$key] = $value; 19 } 20 } 21 else { 22 $array = $object; 23 } 24 return $array; 25 }
1 $array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four'); 2 3 $obj = array2object($array); 4 print $obj->one; // output's "two" 5 6 $arr = object2array($obj); 7 print $arr['foo']; // output's bar