-1

我有这样的数据:

{
"1":{
    "id":"1",
    "boarding":"",
    "atak":"3",
    "pw":4,
    "zwrotnosc":3,
    "marynarze":130,
    "zolnierze":0},
 "2":{
    "id":"2",
    "boarding":"",
    "atak":"5",
    "pw":4,
    "zwrotnosc":4,
    "marynarze":0,
    "zolnierze":222}
}

我尝试了 for (i in data) 或 for (i = 1; i < data.length; i++) 但这是错误的。

拥有像 php foreach 这样的东西或者像数组 data[1][pw] 这样处理它会很好

编辑:

当我执行 for 循环时,我得到了 194 次迭代,并且 data[i] 保存了数据中的单个字符。

编辑2:

这是我在 json 响应之前的数据:

Array
(
[1] => Array
    (
        [id] => 1
        [boarding] => 
        [atak] => 2
        [pw] => 4
        [zwrotnosc] => 4
        [marynarze] => 146
        [zolnierze] => 0
    )

[2] => Array
    (
        [id] => 2
        [boarding] => 
        [atak] => 5
        [pw] => 5
        [zwrotnosc] => 5
        [marynarze] => 0
        [zolnierze] => 250
    )

)

我用

echo json_encode($players);

编辑3:

它看起来像这样:http: //img20.imageshack.us/img20/4798/screenwlz.png

JSON 看起来不错:http: //img822.imageshack.us/img822/2871/screenmuj.png

编辑:已解决

好的。谢谢

它帮助:

data = jQuery.parseJSON( data );

for (i in data){
   // code
}
4

2 回答 2

2

您可能只是没有意识到 JSfor对键进行迭代。

for(var key in data) {
    var value = data[key];
    // do stuff
}
于 2012-06-28T19:13:03.297 回答
1

您需要运行嵌套for循环:

// var data = <?php echo json_encode($players); ?>;
//            ^                                  ^
//            +----------------------------------+---- no quotes
var data = {
    "1": {
        "id": "1",
        "boarding": "",
        "atak": "3",
        "pw": 4,
        "zwrotnosc": 3,
        "marynarze": 130,
        "zolnierze": 0
    },
    "2": {
        "id": "2",
        "boarding": "",
        "atak": "5",
        "pw": 4,
        "zwrotnosc": 4,
        "marynarze": 0,
        "zolnierze": 222
    }
}
for (var i in data) {
    for (var j in data[i]) {
        console.log("data[" + i + "][" + j + "]", data[i][j]);
    }
}
于 2012-06-28T19:18:11.017 回答