在PHP中解码多个JSON对象

时间:2015-04-07 06:36:17

标签: php json

我正在使用PHP套接字来管理聊天应用程序中的数据,这里是一个示例JSON字符串,我期待从套接字读取:

{ "m_time" : "2015-04-07 11:37:35", "id" : "29", "msg" : "Hai there. This is a test message"}

但有时在套接字中会读取连接的多个对象,如下所示:

{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"}{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"}{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"}

无论是单个物体还是多物体,我怎能json_decode

用于套接字读取的PHP代码:

while(@socket_recv($changed_socket, $buf, READ_SIZE, 0) >= 1)
{
    if(!$buf) logResponse('Socket Read Failed for '. $changed_socket);

    $received_text = $buf; //unmask data
    $tst_msg = json_decode($received_text); //json decode 

    logResponse('Received Data: '. $received_text);
}
// logResponse() is used to write a log file log.html

2 个答案:

答案 0 :(得分:4)

整理你的输入,在每个json字符串后添加逗号,发送方式如下:

{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"},{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"},{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"},

php函数

function json_decode_multi($s, $assoc = false, $depth = 512, $options = 0) {
    if(substr($s, -1) == ',')
        $s = substr($s, 0, -1);
    return json_decode("[$s]", $assoc, $depth, $options);
}

var_dump(json_decode_multi('{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"},{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"},{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"},'));

输出:

array(3) {
  [0] =>
  class stdClass#1 (3) {
    public $m_time =>
    string(19) "2015-04-07 11:37:35"
    public $id =>
    string(2) "30"
    public $msg =>
    string(11) "Hai there 1"
  }
  [1] =>
  class stdClass#2 (3) {
    public $m_time =>
    string(19) "2015-04-07 11:37:36"
    public $id =>
    string(2) "31"
    public $msg =>
    string(11) "Hai there 2"
  }
  [2] =>
  class stdClass#3 (3) {
    public $m_time =>
    string(19) "2015-04-07 11:37:37"
    public $id =>
    string(2) "32"
    public $msg =>
    string(11) "Hai there 3"
  }
}

答案 1 :(得分:-2)

试试这个。在你的数组中不存在对象之间的逗号

<script type="text/javascript">
var json = [
{ "m_time" : "2015-04-07 11:37:35", "id" : "30", "msg" : "Hai there 1"},
{ "m_time" : "2015-04-07 11:37:36", "id" : "31", "msg" : "Hai there 2"},
{ "m_time" : "2015-04-07 11:37:37", "id" : "32", "msg" : "Hai there 3"}
];

$.each(json, function(index, item) {
console.log(item); // this console each string {  } in json array
});
</script>

以下是php代码。

<?php
$arr = array(
array(
"m_time" => "2015-04-07 11:37:35",
"id" => "30",
"msg" => "Hai there 1"
),
array(
"m_time" => "2015-04-07 11:37:35",
"id" => "30",
"msg" => "Hai there 1"
)
);

echo json_encode($arr);
?>