Monday, 08 April 2013 13:54

how to create php multidimensional array to be accessed by javascript

Written by 
Rate this item
(0 votes)

its a tricky part to create a php multidimensional array
which will be accessed by javascript function.most of the
time it's confusing.i am going to show how to solve the
problem -

first the following codes shows how to create a array-
this multidimensional array can be accessed by a index.

<?php
echo '
punarray = new Array(';

$q = mysql_query("SELECT id FROM cats WHERE breed LIKE '%(%'
ORDER BY breed");
$total = mysql_num_rows($q);
$count = 0;
while($i = mysql_fetch_object($q))
{
$breed = $i->id;
$count++;
print("new Array(\n");

$q2 = mysql_query("SELECT bid,name FROM dogs WHERE
kennel ='$kennelid' AND breed = '$breed'");
$total2 = mysql_num_rows($q2);
$count2 = 0;

if ($total2 > 0)
{
while($i2 = mysql_fetch_object($q2))
{
$count2++;
$breederid = $i2->bid;
$breedername = $i2->name;
if ($count2 < $total2)
print("new Array(\"$breedername\", \"$breederid\"),\n");
else
print("new Array(\"$breedername\", \"$breederid\")\n");
}
}

if ($count < $total) print("),\n");else print(")\n");
}
echo ');';

now we can access the array by the following function.
i am here pupulating a dropdown by the values of the
array according to the index.

function fillSelectFromArray(index,dropdown)
{
var array=punarray[index];
var j=0;
for (i = 0; i < itemArray.length; i++) {
dropdown.options[j] = new Option(array[i][0]);
j++;}
}

Read 3187 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.