note 109118 modified in function.json-encode by danbrown
| From: | danbrown@php.net | Date: | Tue, 26 Jun 2012 14:00:07 +0000 |
| Subject: | note 109118 modified in function.json-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188842@lists.php.net to get a copy of this message | ||
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.
--was--
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.
http://php.net/manual/en/function.json-encode.php