将json字符串转换为php关联数组

时间:2016-12-27 22:44:46

标签: php json

不知道为什么这不会转换,我会假设它可能与字符串有关,但我得到np输出。

$string = '[{title : "Comp 1 Product",columns : ["Our Vehicle","Features","Their Vehicle"], items : [["dcq","adv","asdvasdv"],["sdv","sdv","sdv"]]},{title : "qwefqw",columns : ["Section 1","Features","Section 2"],items : [["qqwec","qwe","qwegqwev"]]}]';

print_r(json_decode($string), true);

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:6)

如果你看到:

<?php
    header("Content-type: text/plain");
    $string = '[{title : "Comp 1 Product",columns : ["Our Vehicle","Features","Their Vehicle"], items : [["dcq","adv","asdvasdv"],["sdv","sdv","sdv"]]},{title : "qwefqw",columns : ["Section 1","Features","Section 2"],items : [["qqwec","qwe","qwegqwev"]]}]';
    print_r(json_decode($string), true);
    print_r(json_last_error());
?>

上面的代码返回4,这意味着JSON_ERROR_SYNTAX,这是JSON的语法错误。使用JSON Lint检查时,您的JSON将抛出:

prevoew

您需要将其更正为:

[{
    "title": "Comp 1 Product",
    "columns": ["Our Vehicle", "Features", "Their Vehicle"],
    "items": [
        ["dcq", "adv", "asdvasdv"],
        ["sdv", "sdv", "sdv"]
    ]
}, {
    "title": "qwefqw",
    "columns": ["Section 1", "Features", "Section 2"],
    "items": [
        ["qqwec", "qwe", "qwegqwev"]
    ]
}]

您现在拥有的是 JavaScript对象,而不是有效的JSON

答案 1 :(得分:0)

除了无效的json之外,print_r(json_decode($string), true);不打印任何内容,但返回值。要将结果打印到输出,您需要:

print_r(json_decode($string));

echo print_r(json_decode($string), true);

前者更好。