Page 1 of 1

Can it be done? build a JS array with PHP?

Posted: Tue Jan 27, 2004 12:04 pm
by THEMADGEEK
I am attempting to build a JS array using PHP output from a database to build the actual lines of the array. Everything is actually working so far except for two things.

Here's an example (pertinent info) of the final JS array I want to build:

Code: Select all

<script language=JavaScript>
var 1Array =  new Array("('Select field','',true,true)",
"('AP 1')",
"('AP 2')",
"('AP 3')");
var 2Array =  new Array("('Select field','',true,true)",
"('BI 1')",
"('BI 3')");
var 3Array =  new Array("('Select field','',true,true)",
"('BF 1')",
"('BTL')");
var 4Array =  new Array("('Select field','',true,true)",
"('FG 1')",
"('FG 2')",
"('FG 3')",
"('FG 4')",
"('FG 5')");
</script>
As you can see each Park has a various number of Fields so here's the PHP that I am building the array with:

Code: Select all

while ($row = mysql_fetch_array($result)) &#123; 

$park_id = $row&#1111;'park_id'];
$park_name = $row&#1111;'park_name'];
$field_name = $row&#1111;'field_name'];

   if($row&#1111;'park_name']!=$was_park_name) //don't display if already displayed 
   
       @$array .= 'var $park_id Array =  new Array("(''Select field'','''',true,true)",'; 
	   
   $was_park_name=$row&#1111;'park_name']; 

   @$array .= '"(''field_name'')",'; 
   @$array .= ');';
&#125;
Everything is working fine except the part where I have $park_id Array" I need to get rid of the space so it returns "1Array, 2Array" etc. the other thing is in the final line of the code "@$array .= ');';" I get the ");" after every field when I only need it after the last field in the set. Do I need to do another while statement?

Posted: Tue Jan 27, 2004 12:59 pm
by Gen-ik

Code: Select all

<?php

$arr = array("one","two","three","four","five");

echo "<script type="text/javascript">\r\n";
echo "jsArray = new Array();\r\n";

foreach($arr as $key => $value)
    echo "jsArray[{$key}] = {$value};\r\n";

echo "</script>\r\n";

?>
Should do the trick... or point you in the right direction anyway.

Posted: Tue Jan 27, 2004 5:30 pm
by THEMADGEEK
Sorry to be a nincompoop but you lost me at "$arr =" lol

Where does the $arr = array("one","two","three","four","five"); come from? I need to be able to add and remove arrays dynamically so when parks and fields are added/removed it updates accordingly.

What does $key equal? $park_id?

What does $value equal? $field_name?

I appologize for my stupidity but I'm still learning all this stuff.

Thanks for the help!