note 102735 added to language.types.object

From: Date: Wed, 02 Mar 2011 21:26:52 +0000
Subject: note 102735 added to language.types.object
Groups: php.notes 
Request: Send a blank email to php-notes+get-177509@lists.php.net to get a copy of this message
Have an stdClass and want to convert it recursively to an array, or vice versa? Here's two very simple functions. <?php # A static class of mine, has more conversions in it, yet these two are the relevent ones. final class Convert { # Convert a stdClass to an Array. static public function object_to_array(stdClass $Class){ # Typecast to (array) automatically converts stdClass -> array. $Class = (array)$Class; # Iterate through the former properties looking for any stdClass properties. # Recursively apply (array). foreach($Class as $key => $value){ if(is_object($value)&&get_class($value)==='stdClass'){ $Class[$key] = self::object_to_array($value); } } return $Class; } # Convert an Array to stdClass. static public function array_to_object(array $array){ # Iterate through our array looking for array values. # If found recurvisely call itself. foreach($array as $key => $value){ if(is_array($value)){ $array[$key] = self::array_to_object($value); } } # Typecast to (object) will automatically convert array -> stdClass return (object)$array; } } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 74.94.28.33 ---- Manual Page -- http://www.php.net/manual/en/language.types.object.php Edit -- https://master.php.net/note/edit/102735 Del: integrated -- https://master.php.net/note/delete/102735/integrated Del: useless -- https://master.php.net/note/delete/102735/useless Del: bad code -- https://master.php.net/note/delete/102735/bad+code Del: spam -- https://master.php.net/note/delete/102735/spam Del: non-english -- https://master.php.net/note/delete/102735/non-english Del: in docs -- https://master.php.net/note/delete/102735/in+docs Del: other reasons-- https://master.php.net/note/delete/102735 Reject -- https://master.php.net/note/reject/102735 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#177509) next »