欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php5.2以下版本无json_decode函数的解决方法

程序员文章站 2023-11-30 21:34:40
今天写代码的时候,需要用到json_decode函数,发现php5.2以前的版本没有集成这个函数,不过我们可以通过自定义函数实现。 复制代码 代码如下:function...
今天写代码的时候,需要用到json_decode函数,发现php5.2以前的版本没有集成这个函数,不过我们可以通过自定义函数实现。

复制代码 代码如下:

function json_decode2($json)
{
$comment = false;
$out = '$x=';

for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
else if ($json[$i] == ':') $out .= '=>';
else $out .= $json[$i];
}
else $out .= $json[$i];

if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
}

    eval($out . ';');
return $x;
}

不过这个返回的是array

要返回object 则要用到 service_json类了