note 62470 added to function.get-object-vars

From: Date: Wed, 01 Mar 2006 11:49:54 +0000
Subject: note 62470 added to function.get-object-vars
Groups: php.notes 
Request: Send a blank email to php-notes+get-104624@lists.php.net to get a copy of this message
Hi all, I just wrote a function which dumps all the object propreties and its associations recursively into an array. Here it is.. <?php function object_to_array($obj) { $_arr = is_object($obj) ? get_object_vars($obj) : $obj; foreach ($_arr as $key => $val) { $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val; $arr[$key] = $val; } return $arr; } ?> Example: You have an object like this: fruitsbasket Object ( [Fruits] => Array ( [0] => fruits Object ( [_name] => Mango [_color] => Green [_weight] => 10 ) [1] => fruits Object ( [_name] => Apple [_color] => Red [_weight] => 15 ) [2] => fruits Object ( [_name] => Grape [_color] => Purple [_weight] => 5 ) ) [total_weight] => 30 ) just do: <?php $the_array = object_to_array($the_object); print_r($the_array); ?> it will produce an array: Array ( [Fruits] => Array ( [0] => Array ( [_name] => Mango [_color] => Green [_weight] => 10 ) [1] => Array ( [_name] => Apple [_color] => Red [_weight] => 15 ) [2] => Array ( [_name] => Grape [_color] => Purple [_weight] => 5 ) ) [total_weight] => 30 ) I wish function like this could be usefull for you all. :) ---- Server IP: 202.67.10.139 Probable Submitter: 222.124.10.195 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.get-object-vars.php Edit -- http://master.php.net/note/edit/62470 Del: integrated -- http://master.php.net/note/delete/62470/integrated Del: useless -- http://master.php.net/note/delete/62470/useless Del: bad code -- http://master.php.net/note/delete/62470/bad+code Del: spam -- http://master.php.net/note/delete/62470/spam Del: non-english -- http://master.php.net/note/delete/62470/non-english Del: in docs -- http://master.php.net/note/delete/62470/in+docs Del: other reasons-- http://master.php.net/note/delete/62470 Reject -- http://master.php.net/note/reject/62470 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#104624) next »