Javascript handles the sorting of elements within an array

I have spent time searching for a solution to my issue, but so far, I have not been successful in finding one.

My PHP array is arranged exactly as I need it to be, but when I attempt to display it using JavaScript, the order gets distorted, specifically when it comes to numbers. Although I have simplified the example here, I require this structure and even more arrays nested inside.

Here is the code snippet:

<?php
// array ordered as i need
$data = array(
    "first" => array(
        "test3" => array(),
        "test1" => array(),
        "test2" => array(),
        "30" => array(),
        "31" => array(),
        "35" => array(),
    ),
    "second" => array(
        "test1" => array(),
        "test2" => array(),
    ),
);
?>
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script>
            var data = <?php echo json_encode($data); ?>;
            $(document).on('click', 'input[type=button][name=test]', function() {
                var fields = Object.keys(data['first']);
                for(i=0; i<fields.length; i++) {
                    $('body').append('<p>'+fields[i]+'</p>');
                }
            });
        </script>
    </head>
    <body>
        <input type="button" name="test" value="Test me">
    </body>
</html>

Upon execution, the output is as follows:

30
31
35
test3
test1
test2

The numbers are arranged correctly, but the strings are not! I need to treat the keys as values because they represent names that I want to display. I suspect that when fetching the keys, they are arranged in a new array, and despite my efforts to maintain the order, JavaScript always reorders the array differently.

Could you provide assistance? Thank you :)

Answer №1

Just as a helpful individual mentioned in the comments, JavaScript does not recognize "associative arrays" or maintain a specific order for keys. This is why it is essential to organize your array in a desired order from the start (in PHP) and then convert it for JavaScript usage.

<?php
// Array organized as needed
$data = array(
    "first" => array(
        "test3" => array(),
        "test1" => array(),
        "test2" => array(),
        "30" => array(),
        "31" => array(),
        "35" => array(),
    ),
    "second" => array(
        "test1" => array(),
        "test2" => array(),
    ),
);

// Use this for JSON encoding
$keys_used_in_js = array_keys($data['first']);

?>

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

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

Ajax is working effectively as the first post is successful and the second post is able to retrieve data

UPDATE: I resolved the issue by relocating my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). By doing this, the functions are always re-loaded and attached to the "new" form each time the div is refreshed. ...

Ruby on Rails: Use Jquery AJAX to send extra information when submitting a form

I am currently working on a rails form that requires sending an array created in jQuery to my rails controller. However, I have been struggling to format the data correctly. After some trial and error, I was able to successfully send the jQuery array thro ...

What is the best way to include a RecyclerView row in the WishList feature?

I am looking to incorporate a Wishlist feature similar to Google Play in my app. Each row in my RecyclerView within the QuestionActivity contains a Button (Heart Icon). My goal is for when this heart icon is clicked, the corresponding row in the Recycler ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

Unable to pass observable data when closing the pop-up

return{ // The following code can be found in index.js addItem: function () { alert("working"); Newram.show().then(function (response) `***// Calling show functionin Newram.js***` { var c = response; ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...

Utilizing a variable beyond the confines of the script tag

Is there a way to assign the value of my variable place to my variable address, even though they are not in the same script tag? I want to bind the value and utilize it for fetching data. When I log my variable place, I can see the address, but I am unsure ...

Updating input value in React on change event

This is the code for my SearchForm.js, where the function handleKeywordsChange is responsible for managing changes in the input field for keywords. import React from 'react'; import ReactDOM from 'react-dom'; class SearchForm extends ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...

Guide on designing a form for generating custom URLs

I have a form on my website that generates a URL, but it requires the user to wait until the entire page is loaded in order to function properly. I believe this is because I am using window.onload and should switch to using $(document).ready instead. How ...

Tips for Resolving React.js Issues with setInterval

Is there a way to adjust setInterval in React so that it doesn't count faster than it should at the beginning of my program? Currently, 'var i' is being increased by 2 every second. How can I modify my code to resolve this issue? import Reac ...

Retrieve the direction of panning when the panning stops with hammer.js and limit the possible

I have integrated the hammer.js library along with its jQuery plugin. I followed the documentation and used the following code to initialize it on .game-card-mobile divs: /* Creating a Hammer object for swipeable game cards */ var $gameCard = $('.gam ...

Navigating between socket.io and express using while loops

Currently, I am running an express app with socket.io on my raspberry pi to control an LED panel. The panel is being driven by a while loop that updates the pixels. However, I am looking for a way to modify the parameters of this loop or even switch to a d ...

Exploring Event Listeners in the World of JavaScript and/or jQuery

Is there a more sophisticated way to monitor the execution of a specific function in JavaScript or jQuery? Instead of waiting for an event like $('#mything').click(function(){ //blah }), I prefer to be notified when a particular function is trig ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

Using jQuery to vertically center a div

When a vertical menu on my website is clicked, it pops out from the left side of the screen. The content inside is vertically centered using CSS transformations. While expanding to show sub-items, everything remains centered. However, there's an issue ...

What is the best way to place a background image at the top left and bottom right corners of an HTML element?

I have a paragraph and I would like to visually mark the beginning and end of the paragraph for the user. I have successfully displayed a background image in the upper left corner, but I am unsure how to position the background image in the lower right co ...