【问题标题】:Get specific value from multidimensional array via Jquery per json通过每个json的Jquery从多维数组中获取特定值
【发布时间】:2013-06-04 16:12:54
【问题描述】:

我的 PHP 响应看起来像这个多维数组:

{
"results":
{"id":"153","title":"xyz","description":"abc"}, 
{"id":"154","title":"xyy","description":"abb"},
"filter_color":{"Red":1,"Blue":8},
"count_rows":{"rows":"10"}
}

我想使用 jquery 获取这些数据并在表格中显示数据...但是我如何选择特定的键/值对? (例如,我只想显示结果中的所有描述)。

【问题讨论】:

  • 为此使用 jsonParse
  • 您发布的 JSON 无效顺便说一句:jsonlint.org。在你做任何其他事情之前,你必须修复它。
  • @FelixKling:感谢提示,也许我的帖子中缺少一个字符,但我从我的 php 文件中得到的响应是有效的 json 响应(根据 jsonlint)。
  • @FelixKling:再次感谢您的提示。在第二次检查我的回复后,我注意到确实缺少 [] 括号(在嵌套数组中)。我重写了我的 php 文件,现在它可以工作了 :)

标签: javascript jquery json


【解决方案1】:

如果你的 PHP 数组是这样的:

$myArray = array ( 'results' => array (
                                    array ( 'id' => '153',
                                            'title' => 'xyz',
                                            'description' => 'abc' ),
                                    array ( 'id' => '154',
                                            'title' => 'xyy',
                                            'description' => 'abb' )
                                 ),
                   'filter_color' => array ( 'Red' => 1, 'Blue' => 8 ),
                   'count_rows' => array ( 'rows' => '10' )
           );

使用json_encode() 会给你这个回复:

{
"results":
 [ {"id":"153","title":"xyz","description":"abc"}, 
   {"id":"154","title":"xyy","description":"abb"} ],
"filter_color":{"Red":1,"Blue":8},
"count_rows":{"rows":"10"}
}

你的 jQuery 看起来有点像这样:

$.ajax({
    url: "http://example.com",
    success: function(data) {
        // Then you can do this to print out the description of each result
        // in the browser console... or append the info to a table
        for(var i in data.results) {
            console.log(data.results[i].description);

            $("table").append("<tr><td>" + data.results[i].title + "</td><td>" + data.results[i].description + "</td></tr>");
        }
    }
});

【讨论】:

  • 哦,这是我的错误。我重写了 php 部分,因为我的响应缺少嵌套数组中的括号 []。现在它工作正常:)
猜你喜欢
  • 1970-01-01
  • 2016-09-27
  • 2018-01-01
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多