dongtong7990 2012-06-14 23:09
浏览 39
已采纳

PHP JSON返回Jquery

Iv read a lot of search results regarding how to deal with a JSON array that is returned from an Ajax function, but none seem to fit my problem.

Explain: I am effectively searching through a database in a tree like structure to return all of the child elements of a given element. There may be from 1 to many hundreds of results. All of this grunt work is done in PHP, which then returns a JSON array containing the results, however, I cant seem to work out how to iterate over the result, which looks like this:

{ 
  "Kaz1Kid43343757245": {
    "kaz1KidKid24572649":[],
    "kaz1KidKid24572649Back":[]
  },
  "Kaz1Kid43343757245Back":[]
}

Note that each of the items needs to be returned as an individual ID, but if I try

$.each(obj, function(key, val)
{
    //doing stuff with each item
});

I only get two of the results (Kaz1Kid43343757245 and Kaz1Kid43343757245Back) in the keys while the val's show nothing at all.

What am I doing wrong?

Cheers

MVK

  • 写回答

3条回答 默认 最新

  • dongyao5186 2012-06-15 00:20
    关注

    This is an example of a recursive function, which will loop down into objects it encounters or add the key/value to a new, flat object:

    function flatten(obj) {
        var result = {};
    
        function list(node) {
            $.each(node, function(key, val){
                if (jQuery.isPlainObject(val)) {
                    list(val);
                } else {
                    result[key] = val;
                }
            });
        }
    
        list(obj);
        return result;
    }
    

    http://jsfiddle.net/userdude/nssvk/

    Or a tiny bit fancier way to run the first call:

    http://jsfiddle.net/userdude/nssvk/1/

    Which gives:

    {
        "Kaz1Kid43343757245Back" : []
        "kaz1KidKid24572649"     : []
        "kaz1KidKid24572649Back" : []
    }
    

    Question is, what do you want to do with the "flattened away" keys such as Kaz1Kid43343757245 in your example object?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题