在php中 如何把js对象转成数组?

  1. laravelGuzzleHttp写一个爬虫,抓.net接口的数据,返回为jsonp
  2. 去掉函数后的字符串如下
[{ gid:"10000",gname:"一汽奥迪",gspell:"yiqiaodi",child:[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]
  1. 如何将此字符串转成php的数组?
阅读 4.1k
5 个回答
$str = preg_replace(["/([a-zA-Z_]+[a-zA-Z0-9_]*)\s*:/", "/:\s*'(.*?)'/"], ['"\1":', ': "\1"'], $str);
var_dump(json_decode($str,true));

[{ gid:"10000",gname:"一汽奥迪",gspell:"yiqiaodi",child:[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]这个本身不是php标准的json字符串,key值没有引号。

$data = '[{ "gid":"10000","gname":"一汽奥迪","gspell":"yiqiaodi","child":[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]';
$result = json_decode($data,true);
var_dump($result);

$str = <<<STR
[{ gid:"10000",gname:"一汽奥迪",gspell:"yiqiaodi",child:[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]
STR;
echo preg_replace('/([\w]+:)/','"$1":',$str);

输出

[{ "gid:":"10000","gname:":"一汽奥迪","gspell:":"yiqiaodi","child:":[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]

解码结果

[
    {
        "gid:":"10000",
        "gname:":"一汽奥迪",
        "gspell:":"yiqiaodi",
        "child:":[
            {
                "id":"3999",
                "name":"A3",
                "urlSpell":"aodia3-3999",
                "showName":"奥迪A3",
                "saleState":"在销"
            }
        ]
    }
]
$data = '[{ gid:"10000",gname:"一汽奥迪",gspell:"yiqiaodi",child:[{"id":"3999","name":"A3","urlSpell":"aodia3-3999","showName":"奥迪A3","saleState":"在销"}]}]';
$result = json_decode($data,true);
var_dump($result);
json_decode($data,true);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题