如何将这个对象数组解码为 Php 数组,我使用了 json_decode(),但返回了空
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
您的 JSON 无效,这就是 json_decode 返回 null 的原因。
SyntaxError: Unexpected token i
http://json.parser.online.fr/
http://php.net/manual/en/function.json-decode.php
返回以 json 编码的相应 PHP 类型的值。值 true、false 和 null 分别返回为 TRUE、FALSE 和 NULL。如果无法解码 json,或者编码的数据深度超过递归限制,则返回 NULL。
我还修复了您的 JSON:
[
{
"id": 1,
"name":"rajan",
"class":10
},{
"id":2,
"name":"amrit",
"class":12
},{
"id":3,
"name":"arun",
"class":11
}
]
使用代码修复损坏的 JSON:
$replace_keys = preg_replace("/('w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'('w*)'/i", ':"$1"', $replace_keys);
然后,您可以在 json_decode
中使用$replace_keys
。我不确定这是否是最好的方法,因为 json 中的微小变化可能会破坏它,但它使用提供的示例修复了它。
修复 JSON 的完整代码:
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
$replace_keys = preg_replace("/('w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'('w*)'/i", ':"$1"', $replace_keys);
die($fix_values);