对象与数组互转

Posted on Posted in php
Tips: 本文创建于2014年4月10日,已超过 2 年,内容或图片可能已经失效!

对象转数组

[code lang="php"]
function objectToArray($e) {
$e = ( array ) $e;
foreach ( $e as $k => $v ) {
if (gettype ( $v ) == 'resource')
return;
if (gettype ( $v ) == 'object' || gettype ( $v ) == 'array')
$e [$k] = ( array ) objectToArray ( $v );
}
return $e;
}
[/code]

数组转对象

[code lang="php"]
function arrayToObject($e) {
if (gettype ( $e ) != 'array')
return;
foreach ( $e as $k => $v ) {
if (gettype ( $v ) == 'array' || getType ( $v ) == 'object')
$e [$k] = ( object ) arrayToObject ( $v );
}
return ( object ) $e;
}
[/code]

对象充当数组

[code lang="php"]
$arr = array('nam'=>'张三','gender'=>'male');
$obj = (object)$arr;
$obj->name;
$obj->gender;
[/code]

» 转载请注明来源:若我若鱼 » 对象与数组互转

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × 4 =