Want to convert object to an array in PHP? Initially json_encode() function returns a JSON encoded string for a given value.The json_decode() function changes over it into a PHP array.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php class student { public function __construct($firstname, $lastname) { $this->firstname = $firstname; $this->lastname = $lastname; } } $myObj = new student("Alex", "Stokes"); echo "Before conversion:".'</br>'; var_dump($myObj); $myArray = json_decode(json_encode($myObj), true); echo "After conversion:".'</br>'; var_dump($myArray); ?> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.