如何在php中解码嵌套的json

时间:2015-04-23 05:50:08

标签: javascript php json

我有一个json字符串,如:

[
{
    "message": "Test+sms",
    "sender": "test",
    "billcredit": "0.00",
    "messageStatus": "DND",
    "sendondate": "2015-04-22 15:22:00",
    "provider": "aaaa"
},
{
    "message": "Test+sms",
    "sender": "test",
    "billcredit": "0.00",
    "messageStatus": "DND",
    "sendondate": "2015-04-22 15:22:00",
    "provider": "aaa"
},
{
    "message": "Test+sms",
    "sender": "test",
    "billcredit": "1.00",
    "messageStatus": "DELIVRD",
    "sendondate": "2015-04-22 15:22:00",
    "provider": "aaaa"
},
{
    "message": "Test+sms",
    "sender": "test",
    "billcredit": "1.00",
    "messageStatus": "DND REJECTED",
    "sendondate": "2015-04-22 15:22:00",
    "provider": "aaaa"
}
]

我尝试这样做:

$objs = json_decode($data,true);
foreach ($objs as $obj){
$repor= $obj['messageStatus'];
echo $repor;

但它不起作用。请任何人都可以帮我摆脱这个。请帮我在mysql中按顺序上传$ repor。

3 个答案:

答案 0 :(得分:1)

Working Fine Now Check

$data='[{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22  15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22  15:22:00","provider":"aaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DELIVRD","sendondate":"2015-04-22 15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DND REJECTED","sendondate":"2015-04-22 15:22:00","provider":"aaaa"}]';

$objs = json_decode($data, true);
foreach ($objs as $obj){
    $repor= $obj['messageStatus'];
    echo $repor." ";
}

I have placed only single quotation around json array. Nothing more.

答案 1 :(得分:0)

    $rows = array();
    while($row = mysql_fetch_array($result))
    {
        $rows[] = $row;
    }


    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['Records'] = $rows;
    print json_encode($jTableResult);

答案 2 :(得分:-1)

看起来像几乎 json,但并不完全。

试试这个:

$data = '{"messages":' . $data . '}';
$decoded = json_decode($data, true);
foreach ($decoded['messages'] as $message) {
  $messageStatus = $message['messageStatus'];
  echo $messageStatus;
}