将对象转换为 PHP 中的关联数组
要在 PHP 中将对象转换为关联数组,代码如下−
示例
<?php class department { public function __construct($deptname, $deptzone) { $this->deptname = $deptname; $this->deptzone = $deptzone; } } $myObj = new department("Marketing", "South"); echo "Before conversion:"."
"; var_dump($myObj); $myArray = json_decode(json_encode($myObj), true); echo "After conversion:"."
"; var_dump($myArray); ?>
输出
这将生成以下输出−
Before conversion: object(department)#1 (2) { ["deptname"]=> string(9) "Marketing" ["deptzone"]=> string(5) "South" } After conversion: array(2) { ["deptname"]=> string(9) "Marketing" ["deptzone"]=> string(5) "South" }
示例
现在,我们来看另外一个示例 −
<?php class department { public function __construct($deptname, $deptzone) { $this->deptname = $deptname; $this->deptzone = $deptzone; } } $myObj = new department("Marketing", "South"); echo "Before conversion:"."
"; var_dump($myObj); $arr = (array)$myObj; echo "After conversion:"."
"; var_dump($arr); ?>
输出
这将生成以下输出−
Before conversion: object(department)#1 (2) { ["deptname"]=> string(9) "Marketing" ["deptzone"]=> string(5) "South" } After conversion: array(2) { ["deptname"]=> string(9) "Marketing" ["deptzone"]=> string(5) "South" }
广告