note 78688 added to function.json-encode

From: Date: Tue, 23 Oct 2007 14:31:56 +0000
Subject: note 78688 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-131662@lists.php.net to get a copy of this message
json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that: <?php /** * Convert an object into an associative array * * This function converts an object into an associative array by iterating * over its public properties. Because this function uses the foreach * construct, Iterators are respected. It also works on arrays of objects. * * @return array */ function object_to_array($var) { $result = array(); $references = array(); // loop over elements/properties foreach ($var as $key => $value) { // recursively convert objects if (is_object($value) || is_array($value)) { // but prevent cycles if (!in_array($value, $references)) { $result[$key] = object_to_array($value); $references[] = $value; } } else { // simple values are untouched $result[$key] = $value; } } return $result; } /** * Convert a value to JSON * * This function returns a JSON representation of $param. It uses json_encode * to accomplish this, but converts objects and arrays containing objects to * associative arrays first. This way, objects that do not expose (all) their * properties directly but only through an Iterator interface are also encoded * correctly. */ function json_encode2($param) { if (is_object($param) || is_array($param)) { $param = object_to_array($param); } return json_encode($param); } ---- Server IP: 209.41.74.194 Probable Submitter: 199.64.72.252 ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/78688 Del: integrated -- https://master.php.net/note/delete/78688/integrated Del: useless -- https://master.php.net/note/delete/78688/useless Del: bad code -- https://master.php.net/note/delete/78688/bad+code Del: spam -- https://master.php.net/note/delete/78688/spam Del: non-english -- https://master.php.net/note/delete/78688/non-english Del: in docs -- https://master.php.net/note/delete/78688/in+docs Del: other reasons-- https://master.php.net/note/delete/78688 Reject -- https://master.php.net/note/reject/78688 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#131662) next »