Php 使用jQuery的JSON解析-多维数组

Php 使用jQuery的JSON解析-多维数组,php,jquery,arrays,json,Php,Jquery,Arrays,Json,我在解析json格式的响应数据时遇到了一个问题 来自外部URL的JSON输出: [ { "id": "1", "qtext": "Do you like this product?", "op": [ { "oid": "1", "option": "option1" }, { "oid": "2", "option": "opt

我在解析json格式的响应数据时遇到了一个问题

来自外部URL的JSON输出:

[
{
    "id": "1",
    "qtext": "Do you like this product?",
    "op": [
        {
            "oid": "1",
            "option": "option1"
        },
        {
            "oid": "2",
            "option": "option2"
        },
        {
            "oid": "3",
            "option": "option3"
        },
        {
            "oid": "4",
            "option": "option4"
        }
    ]
  },
    {
    "id": "16",
    "qtext": "How is the quality of this video?",
    "op": []
    }
]
为了解析这个json,我编写了以下jQuery代码:

    $.ajax({
    type: 'POST',
    url: 'jsonexp1.php',
        data: {id:1},
        success: function(data) {
            var pj = $.parseJSON(data);
            $.each(pj,function(k,element){
            $("#content").html($("#content").html()+"<p>"+element.id+" "+element.qtext);
        });
    }
});
$.ajax({
键入:“POST”,
url:'jsonexp1.php',
数据:{id:1},
成功:功能(数据){
var pj=$.parseJSON(数据);
$.each(pj,函数(k,元素){
$(“#content”).html($(“#content”).html()+”“+element.id+”+element.qtext);
});
}
});
我能够从json输出中读取前两项“id”和“qtext”。但是,我无法遍历其他元素


一个指导方针会有所帮助。谢谢

op
在响应中是一个数组,因此您需要另一个
$。每个
循环

success: function(data) {
    $.each(data, function(k, element) {
        $.each(data.op, function() {
            // do something with the data in the item...
            console.log(this.oid);
            console.log(this.option);
        });
        $("#content").append($('<p />', { text: element.id + " " + element.qtext });
    });
}
成功:函数(数据){
$.each(数据、函数(k、元素){
$.each(data.op,function(){
//对项目中的数据执行某些操作。。。
console.log(this.oid);
console.log(this.option);
});
$(“#content”).append($('

',{text:element.id+“”+element.qtext}); }); }

另外,请注意,您可以使用
append()
添加元素。

我建议您:

var htm = '';
$.each(pj,function(k,element){
    htm = $("#content").html() + "<p>" + element.id + " " + element.qtext;
    $.each(pj.op, function(i, o){
       htm = htm + "<p>" + o.oid + " " + o.option;
    });
});
$("#content").html(htm);
var htm='';
$.each(pj,函数(k,元素){
htm=$(“#content”).html()+”“+element.id+”+element.qtext;
$。每个(pj.op,函数(i,o){
htm=htm+“”+o.oid+”+o.option;
});
});
$(#content”).html(htm);

您想要什么元素?您还需要一个
$。当前
$中的each()
。each()
。我希望阅读option&oid这两个选项。我正在尝试使用另一个$。each()看看Rory McCrossan回答谢谢Rory!我正在尝试。感谢您的即时帮助。谢谢Jai。您能帮我在下拉列表中显示o.选项吗?我现在可以解析整个json了。