要将对象转换为PHP中的关联数组,代码如下-
示例<?php
class department {
public function __construct($deptname, $deptzone) {
$this->deptname = $deptname;
$this->deptzone = $deptzone;
}
}
$myObj = new department("Marketing", "South");
echo "转换前:"."\n";
var_dump($myObj);
$myArray = json_decode(json_encode($myObj), true);
echo "转换后:"."\n";
var_dump($myArray);
?>
输出结果
使用json解析和编码的方式转换,这将产生以下输出-转换前:
object(department)#1 (2) {
["deptname"]=>
string(9) "Marketing"
["deptzone"]=>
string(5) "South"
}
转换后:
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 "转换前:"."\n";
var_dump($myObj);
$arr = (array)$myObj;
echo "转换后:"."\n";
var_dump($arr);
?>
输出结果
使用array数组的方式,这将产生以下输出-转换前:
object(department)#1 (2) {
["deptname"]=>
string(9) "Marketing"
["deptzone"]=>
string(5) "South"
}
转换后:
array(2) {
["deptname"]=>
string(9) "Marketing"
["deptzone"]=>
string(5) "South"
}