
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert an Object to Associative Array in PHP
To convert an object to associative array in PHP, the code is as follows−
Example
<?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); ?>
Output
This will produce the following output−
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" }
Example
Let us now see another example −
<?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); ?>
Output
This will produce the following output−
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" }
Advertisements