解码PHP中的多个JSON对象 [英] Decoding multiple JSON objects in PHP

查看:213
本文介绍了解码PHP中的多个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using PHP sockets for managing data in a chat application, here's a sample JSON string I'm expecting from the socket read :

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

但是有时在套接字中读取多个串联的对象,就像这样:

But sometimes in the socket reads multiple objects concatenated, like this :

{ "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?

How can I json_decode no matter if there's a single object or multiple ones ?

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

PHP Code for Socket read:

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

推荐答案

整理输入内容,在每个json字符串后添加逗号,像这样发送:

tidy your input, add commas after every json string, send like this:

{ "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"
  }
}

这篇关于解码PHP中的多个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆