PHP对象(object) 与 数组(array) 的转换例子
数组是PHP的灵魂,非常强大,但有时候面向对象编程也是挺方便的,数组 与 对象 之间切换也是常有的事:
例子一
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9743')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9743>/**
* 数组 转 对象
*
* @param array $arr 数组
* @return object
*/
function array_to_object($arr)
{
if (gettype($arr) != 'array')
{
return;
}
foreach ($arr as $k => $v)
{
if (gettype($v) == 'array' || getType($v) == 'object')
{
$arr[$k] = (object)array_to_object($v);
}
}
return (object)$arr;
}
/**
* 对象 转 数组
*
* @param object $obj 对象
* @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;
}
例子2
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7905')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7905><?php
class Test{
public $a;
public $b;
public function __construct($a) {
$this->a = $a;
}
}
//对象转数组,使用get_object_vars返回对象属性组成的数组
function objectToArray($obj){
$arr = is_object($obj) ? get_object_vars($obj) : $obj;
if(is_array($arr)){
return array_map(__FUNCTION__, $arr);
}else{
return $arr;
}
}
//数组转对象
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);
您可能感兴趣的文章:
php对象转换成数组的实例(兼容多维数组)
PHP 数组字符集编码转换的函数
php数组与对象相互转换方法
PHP对象(object) 与 数组(array) 的转换例子
php 二维数组转树状数组的实例代码
php对象转数组方法
在PHP中处理JSON数组以及对象
php 对象转换数组与数组转换对象的例子(图文)
学习php serialize()与unserialize()的用法
php对象转数组的函数