I have following array.
[searchEngineOrder] => Array
(
[0] => keyword
[1] => Google
[2] => Yahoo
[3] => Bing/MSN
)
[Datagrid] => Array
(
[Brand] => Array
(
[1] => Array
(
[keyword] => About Jetwing Hotels Sri Lanka
[Google] => 1
[Yahoo] => 1
[Bing/MSN] => 1
)
[2] => Array
(
[keyword] => Dining at Jetwing Kurulubedda
[Google] => 1
[Yahoo] => 1
[Bing/MSN] => 1
)
) )
This is php array. (i use json encoding)
Now i want to create table. I used following code.
var headers = data.searchEngineOrder;
var trs = '<tr><td>Brand</td></tr>';
var brands = data.Datagrid.Brand;
for (x in brands) {
trs += '<tr>';
for (y in headers) {
// trs += '<td>'+ brands[x].keyword +'</td>'; This is work
trs += '<td>'+ brands[x].headers[y] +'</td>'; //This is not work
}
trs += '</tr>';
}
$('#keyword-table tbody').html(trs);
As above code brands[x].keyword
or brands[x].Google is work. But when i used keyword or Google as variable it is not work.
Please help me. How can i do it?
What you're looking for is bracketed notation with a string:
brands[x]["keyword"]
In JavaScript, you can access object properties (which is what these are) in two ways:
Using dot notation and a literal property name, e.g. foo.property
.
Using bracketed notation and a string property name, e.g. foo["property"]
.
In this second case, the string doesn't have to be a literal string, it can be the result of any expression — including a variable reference. So:
var k = "keyword";
var value = brands[x][k];