yeah

搜索

计数器

62795

链接

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   
) 
?>

(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           
} 
?>

 

(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
?>

 (2).ArrayObject,可以直接将数组转化为对象

 

<?php
$array = array('1' => 'one',   
               '2' => 'two',   
               '3' => 'three');   
$arrayobject = new ArrayObject($array);   
var_dump($arrayobject)
?>
<?php
object(ArrayObject)#1 (3) {   
  [1]=>   
  string(3) "one" 
  [2]=>   
  string(3) "two" 
  [3]=>   
  string(5) "three" 
} 
?>