note 109118 added to function.json-encode
| From: | nerdbeere2k at googlemail dot com | Date: | Thu, 21 Jun 2012 14:27:52 +0000 |
| Subject: | note 109118 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188736@lists.php.net to get a copy of this message | ||
If you need the JsonSerializable Interface in PHP<5.4... this could help:
$fallback_jsonencode = !interface_exists("JsonSerializable", false);
if($fallback_jsonencode){
interface JsonSerializable{
public function jsonSerialize();
}
function fallback_json_encode($obj){
if(is_numeric($obj)){
return $obj;
} else if(is_string($obj)){
return "\"".$obj."\"";
} else if(is_bool($obj)){
return $obj?"true":"false";
} else if(is_array($obj)){
$parts = array();
$keys = array();
//$assocarr = false;
foreach($obj AS $k => $v){
$parts[$k] = fallback_json_encode($v);
//if(!is_numeric($k)) $assocarr = true;
}
/*if($assocarr){
$out = ""; $sep = "\"";
foreach($parts AS $k => $v){
$out .= $sep.$k."\":".$v;
$sep = ",\"";
}
return "{".$out."}";
} else {*/
return "[".implode(",",$parts)."]";
//}
} else if(is_object($obj)) {
if($obj instanceof JsonSerializable) $obj = $obj->jsonSerialize();
$parts = array();
foreach($obj AS $k => $v){
$parts[] = "\"".$k."\":".fallback_json_encode($v);
}
return "{".implode(",",$parts)."}";
} else return "null";
}
}
Note: This Code runs slightly faster than the PHP 5.4 Implementation on my machine, but it DOES NOT
SUPPORT ASSOCIATIVE ARRAYS like that. Just uncomment the commented section for that and it should
work.
----
Server IP: 203.169.204.174
Probable Submitter: 37.201.224.44
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/109118
Del: integrated -- https://master.php.net/note/delete/109118/integrated
Del: useless -- https://master.php.net/note/delete/109118/useless
Del: bad code -- https://master.php.net/note/delete/109118/bad+code
Del: spam -- https://master.php.net/note/delete/109118/spam
Del: non-english -- https://master.php.net/note/delete/109118/non-english
Del: in docs -- https://master.php.net/note/delete/109118/in+docs
Del: other reasons-- https://master.php.net/note/delete/109118
Reject -- https://master.php.net/note/reject/109118
Search -- https://master.php.net/manage/user-notes.php