简体   繁体   English

如何在JSON对象中访问此嵌套数组?

[英]How can I access this nested array within my JSON object?

I'm using PHP to return a json_encode()'d array for use in my Javascript code. 我正在使用PHP返回json_encode()数组,供我的Javascript代码使用。 It's being returned as: 它被返回为:

{"parent1[]":["child1","child2","child2"],"parent2[]":["child1"]}

By using the following code, I am able to access parent2 > child1 通过使用以下代码,我可以访问parent2 > child1

$.getJSON('myfile.php', function(data)
{
   for (var key in data)
   {
      alert(data[key]);
   }
}

However, this doesn't give me access to child1, child2, child , of parent1 . 但是,这不能让我访问child1, child2, childparent1parent1 child1, child2, child Alerting the key by itself shows 'parent1' but when I try to alert it's contents, I get undefined. 单独警告键显示为“ parent1”,但是当我尝试警告键的内容时,我不确定。

I figured it would give me an object/array? 我想这会给我一个对象/数组? How do I access the children of parent1? 如何访问parent1的孩子?

data[key][0] ? 数据[键] [0]?

The JSON returned should be: 返回的JSON应该是:

{"parent1":["child1","child2","child2"],"parent2":["child1"]}

then you can access them as: 那么您可以通过以下方式访问它们:

var data = {"parent1":["child1","child2","child2"],"parent2":["child1"]}
alert(data['parent1'][0]);
alert(data['parent1'][1]);
alert(data['parent1'][2]);

You're only iterating one level into the object, so it's correct that you're only seeing the parents. 您只需要在对象中迭代一个级别,因此只看到父对象是正确的。 You'll need to descend into those keys to find the children. 您需要进入这些键才能找到子代。

// Generally, avoid the "foreach" form in JavaScript.
for (var i = 0; i < data.length; i++) {
  alert(data[i]); // Parent1[], Parent2[], etc

  var parent = data[i];

  for (var j = 0; j < parent.length; j++) {
    alert(parent[j]); // Child1, Child2, etc
  }
}

Aside, the [] suffix on Parent keys is okay. 另外,Parent键的[]后缀也可以。 It is valid JSON. 有效的JSON。

you can assign it in a variable as follows: 您可以按如下所示将其分配给变量:

var = data[key]; var = data [key];

and then get the contents of the array by using the size of the array. 然后通过使用数组的大小获取数组的内容。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM