| Problem with echo
|
sloth9

msg:4221071 | 9:26 pm on Oct 23, 2010 (gmt 0) | I'm trying to make a select box on my site where the options are determined by a previous selection. To do this I want to populate a javascript array with information from a flat file database. One enrty in the array is a list of options. I've exploded the info from the database into PHP arrays, but I can't seem to get them into JS arrays properly. Basically when I use echo, the output comes out different from what I would expect and I can't figure out why! My code:
echo "<script language=\"javascript\">\n var cat2list=new Array();\n cat2list[0]=\"\";\n";
for($k=1;$k<=3;$k++){ echo"cat2list[$k]=[";
for($i=0;$i<sizeof($cat2optionlist[$k]);$i++){ if ($i==sizeof($cat2optionlist[$k])-1){ echo "\"".$cat2optionlist[$k][$i][0]."|".$cat2optionlist[$k][$i][1]."\"]\n";} else{ echo "\"".$cat2optionlist[$k][$i][0]."|".$cat2optionlist[$k][$i][1]."\", ";} } }
echo "</script>\n";
The resulting output is: <script language="javascript"> var cat2list=new Array(); cat2list[0]=""; cat2list[1]=["Client 3|", "|3", "Client 2|", "|2", "Client 1|", "|1"] cat2list[2]=["Client 6|", "|6", "Client 5|", "|5", "Client 4|", "|4"] cat2list[3]=["Client 9|", "|9", "Client 7|", "|7", "Client 8|", "|8"] </script> But I need it to look like this: cat2list[1]=["Client 3|3", "Client 2|2", "Client 1|1"] cat2list[2]=["Client 6|6", "Client 5|5", "Client 4|4"] cat2list[3]=["Client 9|9", "Client 7|7", "Client 8|8"] WHAT AM I DOING WRONG?!
|
bedlam

msg:4221195 | 7:09 am on Oct 24, 2010 (gmt 0) | Honestly, I'd say the whole approach is problematic. If you can simply represent the data produced/retrieved by your PHP script in an array, then you can transform it to json [google.com] in one step using PHP's json_encode() function [php.net] (and if you check Example 2 on that page, you'll find you have considerable flexibility in how the JSON object is renedered). -- b
|
migthegreek

msg:4221578 | 12:33 pm on Oct 25, 2010 (gmt 0) | It would really help if you posted what your data array actually looks like. I'm pretty sure it can be solved quickly.
|
sloth9

msg:4223048 | 10:45 pm on Oct 27, 2010 (gmt 0) | I figured it out, my cat2optionlist array was not constructed properly. Thanks to anyone who tried to help. Sorry to waste your time.
|
|
|