JavaScript: Troubleshooting Array Formatting

Seeking assistance with formatting this JavaScript array accurately. It seems like I am overlooking something crucial:

Javascript:

<script type="text/javascript">

    var dimensions = new Array("225","320","480", "--");
    var walls = new Array();
    walls["225"] = new Array("65","55","45","40", "--");
        var wheels["225"] = new Array();
            wheels["225"]["65"] = new Array("R17", "--");
            wheels["225"]["55"] = new Array("R17","R18", "--");
            wheels["225"]["45"] = new Array("R17", "--");
           wheels["225"]["40"] = new Array("R18", "--");
    walls["320"] = new Array("70", "--");
        var wheels["320"] = new Array();
            wheels["320"]["70"] = new Array("R20","R24", "--");
    walls["480"] = new Array("65", "--");
        var wheels["480"] = new Array();
            wheels["480"]["65"] = new Array("R28", "--");

</script>

PHP utilized to produce the above JavaScript:

<?php   while($row = mysql_fetch_array($result)) {
    list($dimension, $wall, $wheel) = explode("/",$row['meta_value']); $menu[$dimension][$wall][$wheel] = 1; } 

    $dimensions = implode('","', array_keys($menu));
        print "var dimensions = new Array(\"$dimensions\", \"--\");\n";
        print "\nvar walls = new Array();\n";

    foreach($menu as $dimension => $wall_array) {
        $walls = implode('","', array_keys($wall_array));
            print "walls[\"$dimension\"] = new Array(\"$walls\", \"--\");";
            print "\nvar rims[\"$dimension\"] = new Array();\n";

    foreach($wall_array as $wall => $rim_array) {
        $wheels = implode('","', array_keys($rim_array));
            print "wheels[\"$dimension\"][\"$wall\"] = new Array(\"$wheels\", \"--\");";

    }
} ?>

Your support is much appreciated.

Stu

Answer №1

It is not necessary to use var in front of array assignments, only during the initial definitions.

For example, using var widths = ... is correct, but using var rims["225"] = ... is incorrect and should just be rims["225"] = ....

To fix this issue in your php code that outputs the text, simply remove the "var". Change this:

print "\nvar rims[\"$width\"] = new Array();\n";

To this:

print "\nrims[\"$width\"] = new Array();\n";

This adjustment will resolve the problem. However, it's worth considering a better solution by exploring the json-encode php method.

You can easily convert a structured php data structure into something readable by javascript with a single command. Try replacing your php code with the following (please note that this is just a concept and may require testing):

<?php
    while($row = mysql_fetch_array($result)) { list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }

    print "var widths = " . json_encode(array_keys($menu)) . ";\n";
    print "var sidewalls = " . json_encode($menu) . ";\n";
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Tips for resolving the "Unexpected reserved word" error during the installation of Laravel Jetstream

I have been following the steps outlined on to set up Laravel Jetstream. Upon running artisan jetstream:install, I selected Livewire support, API support, email verification, and PHPUnit support for installation. Next, I executed npm install as per the ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

Failed to locate lodash during npm installation

I recently set up my project by installing lodash and a few other libraries using npm: npm install grunt-contrib-jshint --save-dev npm install grunt-contrib-testem --save-dev npm install sinon --save-dev npm install -g phantomjs npm install lodash --save ...

The drop-down menu selection is non-functional on mobile and iPad devices when using Bootstrap

<div class="panel panel-default"> <select> <option value="B3">B3</option> <option value="B4">B4</option> <option value="B5">B5</option> & ...

Ways to call a method in a subclass component from a functional parent component?

In my redux-store, I have objects with initial values that are updated in different places within the child component. As the parent, I created a stateless functional component like this: const Parent = () => { const store = useSelector(state => s ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

Concatenating Arrays in nodeJS

Here's a code snippet that deals with arrays: const array = [ "apple", "banana", "cherry" ]; I'm trying to create a multiline string like this: const foo = " apple banana cherry "; Is there a way for me to begin a new line with each it ...

Looking to dynamically set a background image using data fetched from an API in a ReactJS project

Looking to incorporate a background image from an API response in ReactJS Here is some sample code: useEffect(() => { axios.get(`https://apiaddress=${API_KEY}`) .then(res=>{ console.log(res); setRetrieved(res.data); console.log(retrieved ...

The problem with Vue JS static links

I'm currently working with a Vue.js application (v2). I've noticed that if I skip visiting the root of the site, the sub-links do not work properly. For example: Visit: Then go to If I directly visit: I encounter the following error messag ...

Having trouble with reactjs and typescript? Getting the error message that says "Type 'string' is not assignable to type 'never'"?

When trying to setState with componentDidMount after an axios request is completed, you may encounter the error message Type 'string' is not assignable to type 'never'. Below is the code snippet: import * as React from 'react&apos ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

Setting up a project with Angular 2 and NodeJS

Hello there, I have some inquiries about organizing the project structure of a MEAN application with Angular2. Initially, I followed the introductory guide on angular.io to create a basic Angular2 app. Now, I am attempting to incorporate this app into a N ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...

Guide on implementing iterative data path in v-for loop using Vue

I'm just starting out with Vue and I want to use image file names like "room1.jpg", "room2.jpg", "room3.jpg" in a loop Below is my code, where the second line seems to be causing an issue <div v-for="(p,i) in products" :key="i"> <img src ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

Tips for extracting valuable insights from console.log()

I'm currently utilizing OpenLayers and jQuery to map out a GeoJson file containing various features and their properties. My objective is to extract the list of properties associated with a specific feature called "my_feature". In an attempt to achi ...