note 114294 added to function.get-object-vars

From: Date: Mon, 03 Feb 2014 16:21:46 +0000
Subject: note 114294 added to function.get-object-vars
Groups: php.notes 
Request: Send a blank email to php-notes+get-198401@lists.php.net to get a copy of this message
function to convert object (with children) to an (associative) array ... recusive <?php // --------------------------------------------------------- // ----- object_to_array_recusive --- function (PHP) ------ // -------------------------------------------------------- // -- arg1: $object = (PHP Object with Children) // -- arg2: $assoc = (TRUE / FALSE) - optional // -- arg3: $empty = ('' or NULL) - optional // -------------------------------------------------------- // ----- return: Array from Object --- (associative) ------ // -------------------------------------------------------- function object_to_array_recusive ( $object, $assoc=1, $empty='' ) { $out_arr = array(); $assoc = (!empty($assoc)) ? TRUE : FALSE; if (!empty($object)) { $arrObj = is_object($object) ? get_object_vars($object) : $object; $i=0; foreach ($arrObj as $key => $val) { $akey = ($assoc !== FALSE) ? $key : $i; if (is_array($val) || is_object($val)) { $out_arr[$key] = (empty($val)) ? $empty : object_to_array_recusive($val); } else { $out_arr[$key] = (empty($val)) ? $empty : (string)$val; } $i++; } } return $out_arr; } // -------------------------------------------------------- // -------------------------------------------------------- ?> Example / Usage: a) return an associative (recusive) array from object $new_arr1 = object_to_array_recusive($my_object); // --- or --- object_to_array_recusive($my_object,TRUE); // --- or --- object_to_array_recusive($my_object,1); b) return a numeric (recusive) array from object (set 2nd argument = FALSE) $new_arr2 = object_to_array_recusive($my_object,FALSE); you can pre-set the Array-Value of Empty (Sub-) Objects in 3rd argument ($empty) // --- eg: NULL --- object_to_array_recusive($my_object,1,NULL); ---- Server IP: 72.52.91.14 Probable Submitter: 72.52.91.14 ---- Manual Page -- http://php.net/manual/en/function.get-object-vars.php Edit -- https://master.php.net/note/edit/114294 Del: integrated -- https://master.php.net/note/delete/114294/integrated Del: useless -- https://master.php.net/note/delete/114294/useless Del: bad code -- https://master.php.net/note/delete/114294/bad+code Del: spam -- https://master.php.net/note/delete/114294/spam Del: non-english -- https://master.php.net/note/delete/114294/non-english Del: in docs -- https://master.php.net/note/delete/114294/in+docs Del: other reasons-- https://master.php.net/note/delete/114294 Reject -- https://master.php.net/note/reject/114294 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198401) next »