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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭