marky
marky

Reputation: 5068

How to display values in a multidimensional JSON array

I'm getting a json multidimensional array (as "data" in the success function of an $.ajax call) from a php/mysql database query. The PHP script sends it to the javascript file like so:

header('Content-Type: application/json');
echo json_encode($arr);

The query can return one or more records from the database.

console.log(data) seems to only give me the first "child" array in the "parent" array. Here's what is in the console:

[{id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…},...]
    0: {id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…}
    1: {id:115, branchStateCovered:MN, branchCountyCovered:Benton,…}
    2: {id:116, branchStateCovered:MN, branchCountyCovered:Carlton,…}
    3: {id:117, branchStateCovered:MN, branchCountyCovered:Chisago,…}
    4: {id:118, branchStateCovered:MN, branchCountyCovered:Cook,…}
    5: {id:119, branchStateCovered:MN, branchCountyCovered:Crow Wing,…}
    6: {id:120, branchStateCovered:MN, branchCountyCovered:Isanti,…}
    7: {id:121, branchStateCovered:MN, branchCountyCovered:Itasca,…}
    8: {id:122, branchStateCovered:MN, branchCountyCovered:Kanabec, branchZipCodesCovered:56358, 55051}
    9: {id:123, branchStateCovered:MN, branchCountyCovered:Lake,…}
    10: {id:124, branchStateCovered:MN, branchCountyCovered:Mille Lacs,…}
    11: {id:125, branchStateCovered:MN, branchCountyCovered:Pine,…}
    12: {id:126, branchStateCovered:MN, branchCountyCovered:Saint Louis,…}
    13: {id:127, branchStateCovered:WI, branchCountyCovered:Douglas,…}

In a different $.ajax call I'm accessing what is always a single-dimensional array with

$('label#branchName').text(data['name']);
$('label#branchAddress').text(data['address']);
etc...

But in this case I need to iterate through each of the arrays and display each of its values in a similar manner as above.

I found this SO post, but it looks like the post author is creating the array in such a way as he knows each "child" array's "name" (producers). Maybe the answer for me is in that post and I'm just not seeing it.

How can I take the outputted multidimensional array and cycle through it to display each of the array's arrays into a table - or whatever I want to do with it on the HTML side?

Upvotes: 1

Views: 1316

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

In the success callback of your $.ajax() call, data is the array, so you can use $.each() to iterate through it:

$.each(data, function(index, element) {
    // use individual element (an object) here, i.e. element.id to get the id
});

Upvotes: 3

Related Questions