note 109118 deleted from function.json-encode by aharvey

From: Date: Tue, 25 Sep 2012 02:22:13 +0000
Subject: note 109118 deleted from function.json-encode by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191001@lists.php.net to get a copy of this message
Note Submitter: nerdbeere2k at googlemail dot com ---- If you need the JsonSerializable Interface in PHP<5.4... this could help: <?php $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.

« previous php.notes (#191001) next »