结合许多JSON对象? - PHP

时间:2012-10-04 11:22:07

标签: php json parsing loops associative-array

我目前正在尝试处理一个相对较大的日志文件,该文件以JSON格式存储游戏信息。任何日志文件都是2000-5000行。

日志文件中的示例输出(保留格式...),注意:我已删除了玩家姓名,SteamID和IP地址以获取自己的隐私:

{"timestamp": "2012-09-16 14:10:36", "event": "log_start", "unixTime": 1347768636}
{"timestamp": "2012-09-16 14:10:36", "event": "player_status", "player": {"name": "PLAYER NICKNAME", "userId": 15, "uniqueId": "STEAM_X:X:XXXXXXX (STEAMID)", "team": 1}, "address": "xxx.xxx.xxx.xxx (IP)", "country": "AU"}
{"timestamp": "2012-09-16 14:10:36", "event": "live_on_3", "map": "de_mirage_csgo", "teams": [{"name": "Terrorists", "team": 2}, {"name": "Counter-Terrorists", "team": 3}], "status": 5, "version": "1.0.0 Beta"}

这就是问题的开始。日志文件的每一行都有效地定义了一个新的JSON对象?我试图逐行解码所有这些对象(将它们存储为关联数组),并从那里尝试通过循环将它们合并到一个PHP数组中。这确实“有效”(在某种意义上没有视觉错误),但是array_merge不会产生任何接近我预期的结果。这是我的代码:

(json_decode($string,TRUE)

任何能够让我朝着正确的方向努力实现我需要的建议或意见都将不胜感激!

由于

1 个答案:

答案 0 :(得分:3)

如果您不想要的话,请澄清您的问题。

如果你想要一个Json数据的数组数组,你可以做

$decodedJsonData = array_map(
    function($jsonString) {
        return json_decode($jsonString, true);
    },
    file('/path/to/logfile')
);

这将逐行将整个文件读入数组,并将json_decode应用于每个行/元素,从而生成该Json数据的数组数组。

对于上面的Json,结果将是(demo

Array
(
    [0] => Array
        (
            [timestamp] => 2012-09-16 14:10:36
            [event] => log_start
            [unixTime] => 1347768636
        )

    [1] => Array
        (
            [timestamp] => 2012-09-16 14:10:36
            [event] => player_status
            [player] => Array
                (
                    [name] => PLAYER NICKNAME
                    [userId] => 15
                    [uniqueId] => STEAM_X:X:XXXXXXX (STEAMID)
                    [team] => 1
                )

            [address] => xxx.xxx.xxx.xxx (IP)
            [country] => AU
        )
    [2] => Array
        (
            [timestamp] => 2012-09-16 14:10:36
            [event] => live_on_3
            [map] => de_mirage_csgo
            [teams] => Array
                (
                    [0] => Array
                        (
                            [name] => Terrorists
                            [team] => 2
                        )

                    [1] => Array
                        (
                            [name] => Counter-Terrorists
                            [team] => 3
                        )

                )
            [status] => 5
            [version] => 1.0.0 Beta
        )
)

更多信息: