json数据大家应该遇到过,不过json_encode和json_decode是php5.0以后加上的内置函数,如果低版本要使用,要加扩展,不过很多时候我们不能改变服务器的配置,那么,我们就可以通过自定函数来实现这两个函数,其实所有的系统内置函数,基本上我们都是可以自己来定义的,前面我有写过一个关于json_decode的自定义函数,不过现在一想,也应该有个json_encode的才对,多以就找了一个感觉挺好的,我们可以通过function_exists来判断一个函数是否被定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
if (!function_exists('json_encode')) { function json_encode($array = array()) { if(!is_array($array)) return null; $json = ""; $i = 1; $comma = ","; $count = count($array); foreach($array as $k=>$v){ if($i==$count) $comma = ""; if(!is_array($v)){ $v = addslashes($v); $json .= '"'.$k.'":"'.$v.'"'.$comma; } else{ $json .= '"'.$k.'":'.json_encode($v).$comma; } $i++; } $json = '{'.$json.'}'; return $json; } } if (!function_exists('json_decode')) { function json_decode($json, $assoc = true) { $comment = false; $out = '$x='; $json = preg_replace('/:([^"}]+?)([,|}])/i', ':"\1″\2′, $json); for ($i=0; $i<strlen($json); $i++) { if (!$comment) { if (($json[$i] == '{') || ($json[$i] == '[')) { $out .= 'array('; } elseif (($json[$i] == '}') || ($json[$i] == ']')) { $out .= ')'; } elseif ($json[$i] == ':') { $out .= '=>'; } elseif ($json[$i] == ',') { $out .= ','; } elseif ($json[$i] == '"') { $out .= '"'; } } else $out .= $json[$i] == '$' ? '\$' : $json[$i]; if ($json[$i] == '"' && $json[($i-1)] != '\\') $comment = !$comment; } eval($out. ';'); return $x; } } |
程序本天成,妙手偶得之!我们只是代码的搬运工!
转载请注明:http://www.521php.com/archives/1369/
2013年07月10日 下午 3:30 未解之谜 | 引用 | #1
博主辛苦,谢谢分享!有空来坐坐!