YII Blog
Yeah Cheung 's Yeah Cheung
yeah
如需合作,请发邮件! (realloveyou@foxmail.com)
热门文章
搜索
计数器
64545
最新留言
链接
最新评论
php对象<=>数组互转
Dec 25, 2009 06:19:57 PM | Comments(0) | Category:PHP学习 | Tags:对象数组互转
1.对象=>数组
(1).强制转换
原对象为
<?php
stdClass Object
(
[name] => main
[text] =>
[parrent] =>
[content] =>
[props] => Array
(
)
[inner] => Array
(
)
[level] => 0
)
?>
<?php
$arr = (array)$obj;
?>
强制转换后的数组
<?php
Array
(
[name] => main
[text] =>
[parrent] =>
[content] =>
[props] => Array
(
)
[inner] => Array
(
)
[level] => 0
)
?>
<?php
stdClass Object
(
[name] => main
[text] =>
[parrent] =>
[content] =>
[props] => Array
(
)
[inner] => Array
(
)
[level] => 0
)
?>
<?php
$arr = (array)$obj;
?>
强制转换后的数组
<?php
Array
(
[name] => main
[text] =>
[parrent] =>
[content] =>
[props] => Array
(
)
[inner] => Array
(
)
[level] => 0
)
?>
(2).用内置函数get_object_vars();
2.数组=>对象
<?php
$array = get_object_vars( $object );
?>
原对象:
<?php
class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e;
}
$test = new foo;
var_dump(get_object_vars($test));
?>
结果为:
<?php
array(2) {
["b"]=> int(1)
["c"]=> NULL
}
?>
$array = get_object_vars( $object );
?>
原对象:
<?php
class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e;
}
$test = new foo;
var_dump(get_object_vars($test));
?>
结果为:
<?php
array(2) {
["b"]=> int(1)
["c"]=> NULL
}
?>
(1).用stdClass转换数组为对象
数组
<?php
$arr = array();
$arr['a'] = 1;
$arr['b'] = 2;
$arr['c'] = 3;
?>
用stdClass转换后:
<?php
$object = new StdClass;
$object->a = 1;
$object->b = 2;
$object->c = 3;
?>
<?php
$arr = array();
$arr['a'] = 1;
$arr['b'] = 2;
$arr['c'] = 3;
?>
用stdClass转换后:
<?php
$object = new StdClass;
$object->a = 1;
$object->b = 2;
$object->c = 3;
?>
(2).ArrayObject,可以直接将数组转化为对象