PHP에서 객체를 연관 배열로 변환하는 코드는 다음과 같습니다-
예시
<?php class department { public function __construct($deptname, $deptzone) { $this->deptname = $deptname; $this->deptzone = $deptzone; } } $myObj = new department("Marketing", "South"); echo "Before conversion:"."\n"; var_dump($myObj); $myArray = json_decode(json_encode($myObj), true); echo "After conversion:"."\n"; 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:"."\n"; var_dump($myObj); $arr = (array)$myObj; echo "After conversion:"."\n"; 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" }