0

My PHP response looks like this multidimensional array:

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

With jquery I want to fetch this data and display the data in a table... But how could I select a specific key/value pair? (e.g. I just want to show all descriptions from my result).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
John Brunner
  • 2,842
  • 11
  • 44
  • 85
  • use jsonParse for this – karthikr Jun 04 '13 at 16:14
  • 1
    possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Jun 04 '13 at 16:21
  • 1
    The JSON you posted is invalid btw: http://jsonlint.org/. Before you do anything else, you have to fix it. – Felix Kling Jun 04 '13 at 16:22
  • @FelixKling: thans for the hint, maybe a character is missing in my post, but the reponse I get from my php file is a valid json response (according to jsonlint). – John Brunner Jun 04 '13 at 16:47
  • @FelixKling: Thanks again for the hint. after checking my response a second time, I noticed that there was indeed the [] brackets missing (at the nested array). I rewrote my php file, now it works :) – John Brunner Jun 04 '13 at 17:03

1 Answers1

2

If your PHP array is like this:

$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' )
           );

Which would give you this response using 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"}
}

And your jQuery looks a little like this:

$.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>");
        }
    }
});
Jon
  • 12,684
  • 4
  • 31
  • 44
  • oh, it was my mistake. i rewrote the php part because my response was missing the brackets [] in the nested array. now it works fine :) – John Brunner Jun 04 '13 at 17:02