问题描述
我正在使用PHP创建一个非常大的多维数组.每个对象都包含名称,ID,ParentID和子级.子级是由更多相同格式的对象组成的数组.
I am creating an very large multidimensional array using PHP. Each object contains Name, ID, ParentID and Children. Children is an array of more objects in the same format.
至关重要的是,我要命名每个对象的ID-这有助于我将每个对象放在正确的父对象下. (在下面的代码中,我使用101、102等.)
It is critical I name the IDs of each object - this helps me put each object under the correct parent. (In the code below, I use 101, 102 etc.)
但是,我遇到的问题是当我使用json_encode
返回JSON中的数组时.每个儿童"数组都将被打印为对象,而不是数组-如下面的JSON代码所示.
However, the problem I am having is when I return the array in JSON using json_encode
. Each 'Children' array is being printed as an object, not an array - as shown in the JSON code below.
我在此处上读到另一个SO线程时,它们由于包含字符串键而成为对象" -尽管它们是数字,但它们仍然是字符串.
As I read on another SO thread here, they "are made as objects because of the inclusion of string keys" - although they are numbers, they are still strings.
{
"101": {
"ID": "101",
"ParentID": "0",
"Name": "Root One"
"Children": {
"102": {
"ID": "102",
"ParentID": "101",
"Name": "Child One"
},
"103": {
"ID": "103",
"ParentID": "101",
"Name": "Child Two",
"Children": {
"104": {
"ID": "104",
"ParentID": "103",
"Name": "Child Child One"
}
}
},
有人知道如何克服这个问题吗?
Does anyone know how to overcome this issue?
JSON应该看起来像这样(方括号很重要!):
The JSON should look like this (the square brackets are important!):
[
{
"ID": "101",
"ParentID": "0",
"Name": "Root One",
"Children": [
{
"ID": "102",
"ParentID": "101",
"Name": "Child One",
"Children": [
推荐答案
我现在有了一个快速有效的可行解决方案.
I have now got a working solution which is fast and works well.
-
首先,按照问题的SO链接编写;
Firstly, as written in SO link from the question;
在JSON中;弯括号可容纳对象({}
),方括号可容纳数组([]
).
In JSON; Curly braces hold objects ({}
), Square brackets hold arrays ([]
).
因此,使用字符串作为键将导致json_encode
函数返回对象,而重置键将确保其创建数组.
So using a string as a key will result in the json_encode
function returning objects, whereas reseting the keys will ensure it creates arrays.
因此,在返回JSON编码的字符串之前,我运行了一个函数来重置所有数组键.我在此SO线程(在多维数组中重置数组键)中找到的代码特别有用!
Therefore, just before I return my JSON encoded string, I run a function to reset all the array keys. The code I found on this SO thread (Reset array keys in multidimensional array) was particularly useful!
这篇关于多维数组上的json_encode()-带字符串键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!