Hi folks,
I’m trying to create a two dimensional javascript array from the contents of an sql database. I need it to take the form:
array[row 0][field 0];
array[row 0][field 1];
array[row 0][field 2];
array[row 1][field 0];
array[row 1][field 1];
etc etc, flexible to accommodate however many rows and fields there are in the database table.
I’ve sussed out how to convert a php array to javascript (easy using json_encode($array)). The problem I’m having is rendering it in the requitred format. I’m pretty new to all this so its’ highly likely that the answer will be obvious and simple but I’ve come up against a brick wall and would appreciate some help.
The relevant code I’ve written so far is as follows:
[php]$result = mysql_query(“SELECT * FROM exampleTable ORDER BY ID”) or die(‘No table found’);
while ($row = mysql_fetch_array($result)){
$array[] = $row;
}
echo ‘var array = ’ .json_encode($array).’;’;[/php]
Which does, admittedly, return the contents of the database table but not in a format that is useful or usable for what I want to do. I was thinking of something along the lines of:
[php]$result = mysql_query(“SELECT * FROM exampleTable ORDER BY ID”) or die(‘No table found’);
$array = array();
for($i=0; $i<=4;$i++){
for($ii=0; $ii<=4;$ii++){
$array[] = array();
$array[$i][$ii] = array($row[$i]$col[$ii]);
}
}
echo 'var array = ' .json_encode($array).';';[/php]
… but this is leading to all sorts of problems. In short I’m having problems with the syntax around the for loop for generating the array and after many hours trawling the net for clues am no closer to getting it to work. Like I say, any help would be much appreciated.
Many thanks
Stef