【问题标题】:json array loop thru nested not workingjson数组循环通过嵌套不起作用
【发布时间】:2013-07-28 10:58:36
【问题描述】:

我正在尝试循环遍历我的 json 对象的嵌套数组..

这是循环:

        $("#test").text("");
        for(var i=0;i<obj.length;i++){
            $("#test").append(obj[i].line_item + ", ");
            for(var j=0;j<obj[i].length;j++){
                $("#test").append(obj[i][j].iid + ", ");
                $("#test").append(obj[i][j].name + ", ");
                $("#test").append(obj[i][j].price + ", ");
                $("#test").append(obj[i][j].lid + ", ");
                $("#test").append(obj[i][j].picture + "<br />");
            }//for for
        }//for

console.log 我没有显示任何错误,当我回显 php 脚本时,我得到以下输出:

[{"line_item":"base","0":
{"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
"1":{"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}}]

问题: 当我遍历数组时,我只得到输出:base,在我的 html 文件中。

我的问题:如何获取内部数组对象?

【问题讨论】:

    标签: php jquery ajax json multidimensional-array


    【解决方案1】:

    我猜你正在尝试这样做:

    var a = [];
    
    $.each(obj, function(i, arr) {
        a.push(arr.line_item);
        $.each(arr, function(j, ob) {
            if (typeof ob == 'object') {
                $.each(ob, function(key,value) {
                    a.push(value)
                });
            }
        });
    });
    
    $("#test").text(a.join(', '));
    

    FIDDLE

    【讨论】:

    • 这成功了!!多谢!想退出一段时间了!
    【解决方案2】:

    那是因为你使用的是对象而不是数组,所以你不能这样做:

     obj[i].length
    

    一个简单的解决方法是将项目放入一个数组中,示例 JSON:

    [{"line_item":"base", "items": [
    {"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
    {"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}]}]
    

    并将您的代码更改为:

    $("#test").text("");
    for(var i=0;i<obj.length;i++){
      $("#test").append(obj[i].line_item + ", ");
      for(var j=0;j<obj[i]['items'].length;j++){
        var item = obj[i]['items'][j];
        $("#test").append(item.iid + ", ");
        $("#test").append(item.name + ", ");
        $("#test").append(item.price + ", ");
        $("#test").append(item.lid + ", ");
        $("#test").append(item.picture + "<br />");
      }//for for
    }//for
    

    【讨论】:

    • 也会对此进行调查!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2016-04-02
    相关资源
    最近更新 更多