PHP custom Json_encode () and Json_decode () functions

Source: Internet
Author: User

JSON data you should have encountered, Json_encode () and Json_decode () php5.0 is added after the built-in function, if the lower version to use, need to expand, many times we do not have the right to change the configuration of the server, we can only through the custom function to implement these two functions, in fact, all the system built-in functions, basically we can be defined by ourselves.

if(!function_exists(' Json_encode ')) {functionJson_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 ')) {functionJson_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;}}

PHP custom Json_encode () and Json_decode () functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.