Reputation: 13672
I'm generating a 2-column HTML table from a php array as follows:
<table>
<?php
$i=0
foreach ($fullNameArray as $namePair){
echo
"<tr>
<td id='first ".$i."'>".$namePair[0]."</td>
<td id='last".$i."'>".$namePair[1]."</td>
</tr>";
$i++;
}
?>
</table>
What is the best way to explore this table in Javascript, for example to build an array that would replicate the PHP array, i.e., an array of [first name, last name] pairs.
Upvotes: 0
Views: 947
Reputation: 6930
If you want to go the old-fashioned pure-JavaScript way, you could do some simple DOM traversal.
If you add an id
to the table, your life will be much easier, especially if you have (or may later add) other tables in the page.
<table id="nameTable">
...
</table>
Now you can access the table in JavaScript and store a reference to it in a variable. You will also want to initialize an empty array/list variable to hold the names later.
var nameTable = document.getElementById("nameTable");
var nameArray = [];
Next, you begin looping through the child elements of the table, each of which will be a tr
(table row) element.
for (var i=0; i<nameTable.childNodes.length; i++) {
...
}
Inside that for
loop you will build your list of [first name, last name] pairs. You will do this by grabbing the value of each of the two td
(table data cell) children of the current row.
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
That should give you a JSON array something like this (my values added):
[
["Andy", "Jackson"],
["Barry", "Obama"],
["Benny", "Franklin"],
["Georgey", "Washington"],
["Billy", "Clinton"]
]
To review, the full code would look something like this:
var nameTable = document.getElementById("nameTable");
var nameArray = [];
for (var i=0; i<nameTable.childNodes.length; i++) {
var dataCells = nameTable.childNodes[i].childNodes;
var namePair = [dataCells[0].innerHTML, dataCells[1].innerHTML];
}
NOTE: This is fun, but it is likely that the better solution, if you don't mind a hard-coded JSON array in your source code (if you've got the table there anyway it really doesn't matter), is probably to print a json_encode
d array in a <script>
tag straight from the PHP, like @JayBhatt suggested. It is likely the faster method, and it puts much less stress on the user's browser.
Upvotes: 1
Reputation: 820
Another way could be assign the json to a hidden input instead a javascript and later get the input value in your javascript Code.
Upvotes: 1
Reputation: 5651
Encode your array to Json using PHP's json_encode, assign this string to a javascript variable and decode json to array using javascript...
Upvotes: 1