1. 程式人生 > >php 對象數組互轉

php 對象數組互轉

p s 互轉 ria pac pri put ray font cti

數組轉對象 function array2object($array) { if (is_array($array)) { $obj = new StdClass(); foreach ($array as $key => $val){ $obj->$key = $val; } } else { $obj = $array; } return $obj; } $array = array(‘foo‘ => ‘bar‘,‘one‘ => ‘two‘,‘three‘ => ‘four‘); $obj = array2object(
$array); print $obj->one; // output‘s "two" 對象專屬組 function object2array($object) { if (is_object($object)) { foreach ($object as $key => $value) { $array[$key] = $value; } } else { $array = $object; } return $array; }

$obj = Object
(
[foo] => bar
[one] => two
[three] => four
)

$arr = object2array($obj); print $arr[‘foo‘]; // output‘s bar

php 對象數組互轉