将JSON转换为PHP数组

时间:2015-03-10 04:39:02

标签: php json

我向PHP发送包含多个项目的JSON帖子。我的JSON看起来像这样:

 [
    {
        "request": "submitTicket",
        "id": "3",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "123.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    },
    {
        "request": "submitTicket",
        "id": "4",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "143.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    },
    {
        "request": "submitTicket",
        "id": "5",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "122.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    }
]

我一直在尝试在PHP中使用json_decode(),但它返回null,导致foreach循环失败。为什么解码不起作用?

实际上,这个JSON在到达PHP时会收回插入的斜杠。我在发布之前把它们拿出来并尝试用stripslashes()运行它。

4 个答案:

答案 0 :(得分:1)

试试这个..

$data ='[

{"request":"submitTicket","id":"3","delivLoc":"1 COLORADO CITY","estimatedBarrels":"123.0","facilityID":"T666778","highDegreeF":"0.0","highOilFeet":"0"},
{"request":"submitTicket","id":"4","delivLoc":"1 COLORADO CITY","estimatedBarrels":"143.0","facilityID":"T666778","highDegreeF":"0.0","highOilFeet":"0"},
{"request":"submitTicket","id":"5","delivLoc":"1 COLORADO CITY","estimatedBarrels":"122.0","facilityID":"T666778","highDegreeF":"0.0","highOilFeet":"0"}

]';

$jsonarray=json_decode($data,true);
print_r($jsonarray);

答案 1 :(得分:1)

在与大家的建议一起玩之后,我想出来了。在尝试解码JSON之前,我不得不从帖子中删除斜杠。我像这样解码为PHP数组:

$data = json_decode(stripslashes($_POST['json']));

我想昨晚已经太晚了,我有些忽视了这一点。感谢大家的帮助和快速回复。

答案 2 :(得分:0)

试试这个。

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

<强>输出:

 object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

答案 3 :(得分:0)

我能看到的是传递的实际数据可能无效json。

只需在变量中分配数据并像这样使用

var data = [{
        "request": "submitTicket",
        "id": "3",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "123.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    },
    {
        "request": "submitTicket",
        "id": "4",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "143.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    },
    {
        "request": "submitTicket",
        "id": "5",
        "delivLoc": "1 COLORADO CITY",
        "estimatedBarrels": "122.0",
        "facilityID": "T666778",
        "highDegreeF": "0.0",
        "highOilFeet": "0"
    }
]

然后用数据部分中的ajax(我假设你使用的是ajax)传递这个

$.ajax({
    url:[your url],
    data:data,
    ....
});

希望这会有用