Can someone assist me with formatting this JavaScript array correctly? I am obviously missing something fundamental:
Javascript:
<script type="text/javascript">
var widths = new Array("225","320","480", "--");
var sidewalls = new Array();
sidewalls["225"] = new Array("65","55","45","40", "--");
var rims["225"] = new Array();
rims["225"]["65"] = new Array("R17", "--");
rims["225"]["55"] = new Array("R17","R18", "--");
rims["225"]["45"] = new Array("R17", "--");
rims["225"]["40"] = new Array("R18", "--");
sidewalls["320"] = new Array("70", "--");
var rims["320"] = new Array();
rims["320"]["70"] = new Array("R20","R24", "--");
sidewalls["480"] = new Array("65", "--");
var rims["480"] = new Array();
rims["480"]["65"] = new Array("R28", "--");
</script>
PHP used to generate the above JavaScript:
<?php while($row = mysql_fetch_array($result)) {
list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }
$widths = implode('","', array_keys($menu));
print "var widths = new Array(\"$widths\", \"--\");\n";
print "\nvar sidewalls = new Array();\n";
foreach($menu as $width => $sidewall_array) {
$sidewalls = implode('","', array_keys($sidewall_array));
print "sidewalls[\"$width\"] = new Array(\"$sidewalls\", \"--\");";
print "\nvar rims[\"$width\"] = new Array();\n";
foreach($sidewall_array as $sidewall => $rim_array) {
$rims = implode('","', array_keys($rim_array));
print "rims[\"$width\"][\"$sidewall\"] = new Array(\"$rims\", \"--\");";
}
} ?>
Thank you in advance for your help
Stu
You shouldn’t be putting
varin front of array assignments, just the initial definitions.So
var widths = ...is fine, butvar rims["225"] = ...is incorrect and should just berims["225"] = ....Change your php; in the line of code that outputs that text remove the “var”. Change this:
To this:
That will solve your problem. But really, this overall solution is not the best. You ought to consider looking into the
json-encodephp method.You can take a fully-structured php data structure and with this one command convert to something that can be read by javascript. Try replacing your php with the below and see what happens (note that this is untested, but this is the basic idea):