如何将高度嵌套的 php 数组/对象编码为 JSON?

注意:这似乎很长,这里有一个简短的解释,供那些不想(或不需要)看到我下面所有长解释的人使用。如果我在这里放了太多东西,我很抱歉,但我认为提供太多信息比提供太少信息要好。


简而言之,我有一个充满对象的 JS 数组。这些对象的一些属性是数组。这些数组是对象,里面有数组,里面有对象。总而言之,有 5 层嵌套。JavaScript 的 JSON.parse/stringify 在这些方面工作得很好,但是当开始让这个程序在服务器上工作时,我使用 JavaScript 的 JSON.stringify 发送一些数据并使用 php 的 json_decode 来读取它。php 摆弄数据,用它来编辑大对象(以 JSON 格式存储在服务器上的 txt 文件中)。像 addMessage 和 createRoom 这样的小函数可以工作,但是当我尝试发送一个 3 级对象时它不起作用。我认为问题可能与尝试上传字符串化对象有关,因为我的其他 php 脚本接收参数,然后从这些参数创建对象为 stdClass。


长无聊版:


这个问题似乎在其他地方的变体中被问到,但我找不到适合我的答案。基本上,我正在开发一个在线交互式白板程序。它使用 JS 作为主要语言和 PHP 来完成所有的文件编写工作。我使用 json_encode 将数据存储在 .txt 文件中。为了从文件中读取数据,我的 JS 调用我的 php,它解码文件、获取相关数据、对其进行编码并回显。所有的数据都是由 JS 生成的,并且是面向被 JS 编辑的——所有的数据都是由 JS Classes 构建的。到目前为止,我的程序运行良好,加入/创建白板和聊天功能相对简单。当我尝试实现跨计算机白板同步时,我发现当我将新的白板数据发送到php并尝试将其放入文件时,json_encode 失败。我从 Apache 日志中收到此错误:PHP Recoverable fatal error:  Object of class stdClass could not be converted to string.

它没有停止程序,而是继续并破坏数据文件(可能需要在那里进行一些检查)并杀死整个程序。这就是我的数据结构的工作方式(在 JS 中,如果我对其进行硬编码,它将是这样):


[ /* list of room objects */

    { /* a room object */

        name: 'example', 

        id: 'numbers', 

        whiteboardData: [

           { /* a shape object */

            color: [r, g, b],

            pointList: [

                { /* a vector object*/

                    x: 100,

                    y: 100,

                }

                /* heaps of other vector objects */

            ]

            }

        ], /* end of whiteboardData */

        chatMessages: [

            { /* a message object */

                sender: 'username',

                content: 'hi'

            }

            /* heaps of other message objects */

        ]

    }

    /* heaps of other room objects */

]



莫回无
浏览 67回答 1
1回答

犯罪嫌疑人X

那里的噪音太多了,我无法轻松地看出问题所在。我不会尝试推理出来,而是向您展示一个解决方案,它接收数据就像您硬编码它一样,向whiteboardData数组添加一个新元素,然后再返回它。我希望使用 fetch 而不是旧的 XMLHttpRequest,但我有点生疏了。这对我来说更容易。HTML<!doctype html><html><head><script>"use strict";function byId(id){return document.getElementById(id)}window.addEventListener('load', onLoaded, false);var jsonObj =&nbsp;[ /* list of room objects */&nbsp; &nbsp; { /* a room object */&nbsp; &nbsp; &nbsp; &nbsp; name: 'example',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; id: 'numbers',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; whiteboardData: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { /* a shape object */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color: [100, 150, 100],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pointList: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { /* a vector object*/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x: 100,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y: 100,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /* heaps of other vector objects */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ], /* end of whiteboardData */&nbsp; &nbsp; &nbsp; &nbsp; chatMessages: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { /* a message object */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sender: 'username',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; content: 'hi'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; /* heaps of other message objects */&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }&nbsp; &nbsp; /* heaps of other room objects */];function ajaxPostFormData(url, formData, onSuccess, onError){&nbsp; &nbsp; var ajax = new XMLHttpRequest();&nbsp; &nbsp; ajax.onload = function(){onSuccess(this);}&nbsp; &nbsp; ajax.onerror = function(){onError(this);}&nbsp; &nbsp; ajax.open("POST",url,true);&nbsp; &nbsp; ajax.send(formData);}function onLoaded(evt){&nbsp; &nbsp; let fd = new FormData();&nbsp; &nbsp; fd.append('whiteboardData', JSON.stringify(jsonObj) );&nbsp; &nbsp; ajaxPostFormData('blahBlah.php', fd, function(ajax){console.log(ajax.responseText)}, function(){} );}</script></head><body></body></html>PHP<?php// blahBlah.php&nbsp; &nbsp; var_dump($_POST['whiteboardData']);&nbsp; &nbsp; $jsonObj = json_decode( $_POST['whiteboardData'] );&nbsp; &nbsp; $newObj = new wbData(200,300,200, [new vec2d(0,0), new vec2d(10,10), new vec2d(100,100)] );&nbsp; &nbsp; // append the new stuff&nbsp; &nbsp; $jsonObj[0]->whiteboardData[] = $newObj;&nbsp; &nbsp; var_dump( json_encode($jsonObj) );//-----------------------------------&nbsp; &nbsp; class wbData&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public function __construct ($r,$g,$b, $pts=[])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->color = [$r, $g, $b];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //$this->pointList = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->pointList = $pts;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; class vec2d&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public function __construct($x=0, $y=0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->x = $x;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->y = $y;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }?>结果在控制台string(164) "[{"name":"example","id":"numbers","whiteboardData":[{"color":[100,150,100],"pointList":[{"x":100,"y":100}]}],"chatMessages":[{"sender":"username","content":"hi"}]}]"string(250) "[{"name":"example","id":"numbers","whiteboardData":[{"color":[100,150,100],"pointList":[{"x":100,"y":100}]},{"color":[200,300,200],"pointList":[{"x":0,"y":0},{"x":10,"y":10},{"x":100,"y":100}]}],"chatMessages":[{"sender":"username","content":"hi"}]}]"
打开App,查看更多内容
随时随地看视频慕课网APP