note 75386 deleted from function.json-encode by danbrown

From: Date: Sat, 18 Sep 2010 15:44:30 +0000
Subject: note 75386 deleted from function.json-encode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-172714@lists.php.net to get a copy of this message
Note Submitter: sean at awesomeplay dot com ---- jtconner, That code is horrendously broken for an array that contains anything other than integer values. You need to do things much better than that to handle any kind of real-world data. Here's something similar to what I use (off the top of my head). Note that it will break horribly on recursive arrays. Disclaimer: this is off the top of my head, it might have a few typos or other mistakes. function jsValue(&$value) { switch(gettype($value)) { case 'double': case 'integer': return $value; case 'bool': return $value?'true':'false'; case 'string': return '\''.addslashes($value).'\''; case 'NULL': return 'null'; case 'object': return '\'Object '.addslashes(get_class($value)).'\''; case 'array': if (isVector($value)) return '['.implode(',', array_map('jsValue', $value)).']'; else { $result = '{'; foreach ($value as $k=>$v) { if ($result != '{') $result .= ','; $result .= jsValue($k).':'.jsValue($v); } return $result.'}'; } default: return '\''.addslashes(gettype($value)).'\''; } NOTE: the isVector() function call is one that checks to see if the PHP array is actually a vector (an array with integer keys starting at 0) or a map (an associative array, which may include a sparse integer-only-keyed array). The function looks like: function isVector (&$array) { $next = 0; foreach ($array as $k=>$v) { if ($k != $next) return false; $next++; } return true; } By using that test, it's guaranteed that you will always send correct results to Javascript. The only time that might fail is if you have a vector and delete a few keys without compacting the array back down - it'll detect it as a map. But, technically, that's correct, since that's how PHP arrays behave. The function is capable of taking any PHP type and returning something, and it should be impossible to get it to return anything that's un-safe or incorrect.

« previous php.notes (#172714) next »