List Info

Thread: note 78688 added to function.json-encode




note 78688 added to function.json-encode
user name
2007-10-23 09:31:56
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  -- h
ttps://master.php.net/note/delete/78688/integrated
Del: useless     -- http
s://master.php.net/note/delete/78688/useless
Del: bad code    -- htt
ps://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     -- http
s://master.php.net/note/delete/78688/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78688
Reject      -- https://mast
er.php.net/note/reject/78688
Search      -- https://
master.php.net/manage/user-notes.php

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1]

about | contact  Other archives ( Real Estate discussion Medical topics )