Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm:

  • The result of my json_encode() operation in the output file: ["1","96","32","33","4","48","74","19","23","43","8","8","46","36","92","81","81","64","26","96","82","85","80","24","61","4","46","32","68","11","63","14","98","20","66","17","28","58","32","16","33","47","80","94","5","68","35","28","24","85","38","12","79","57","6","47","18","15","34","18","91","63","67","73","86","16","71","29","14","79","18","10","97","29","1","97","72","92","42","19","25","76","38",...

  • After applying JSON.parse(), I receive my array back in a variable unsortedArray with:

  • Index: 0

  • Value: 1,96,32,33,4,48,74,19,23,43,8,8,46,36,92,81,81,64,26,96,82,85,80,24,61,4,46,32,68,11,63,14,98,20,66,17,28,58,32,16,33,47,80,94,5,68,35,28,24,85,38,12,79,57,6,47,18,15,34,18,91,63,67,73,86,16,71,29,14,79,18,10,97,29,1,97,72,92,42,19,25,76,38,25,21,37

However, upon running it through a sorting algorithm like Bublesort (acknowledging it's not the most efficient), the output seems unusual:

[0] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 10
            [3] => 11
            [4] => 12
            [5] => 14
            [6] => 14
            [7] => 15
            [8] => 16
            [9] => 16
            [10] => 17
            [11] => 18
            [12] => 18
            ...
            ...
            [84] => 97
            [85] => 98
        )

I invoke the sorting function along with the input this way

bubleSort.apply(this, unsortedArray);
.

As displayed above, the data is not fully sorted; everything except certain numbers (1, 4, 5, 6, and 8) are arranged. This behavior puzzles me.

Update:

The $jobRetParam contains all results from another page, which serves as an output of JavaScript code sent using POST to the site via this piece of code:

$jobRetParam = $_REQUEST['results'];

The $allOutputVarPath variable is initialized here:

$allOutputVarPath = array();
    $i = 0;
    foreach ($allOutputVar as $key => $values) {
        foreach ($values as $key => $value) {
            if ($key == 4) {
                $allOutputVarPath[] = array($value => $jobRetParam[$i]);
                $i++;
            }
        }
    }

The $allOutputVar originates from a Database where $key == 4 represents the $value holding the path for use in the $path variable within the subsequent loop. The statement $jobRetParam[$i] is elaborated right after the "Update" section, assigning each $value with its corresponding results.

...

I possess extensive code, but it ultimately boils down to this when encoding to Json:

foreach ($allOutputVarPath as $key => $values) {
        foreach ($values as $path => $fileContent) {
            $writeSuccess = wrtieToHDD($path, "w", $fileContent);
        }
}

Here's a sample of $path => $fileContent utilized as input in the wrtieToHDD() function for encoding the $fileContent into Json.

  • $path: [.../sorted2.txt]

  • $fileContent: Array ( ... )

And here's the wrtieToHDD() function:

function wrtieToHDD ($destination, $fopenMode, $content) {
    $handle = fopen($destination, $fopenMode);

    // checking if $content is an array
    if (gettype($content) == "array" or "object") {

        // encode as json
        $content = json_encode($content);
    }

    // writing into the file
    $writeContent = FALSE;
    if (flock($handle, LOCK_EX)) { 
        fwrite($handle, $content);
        fflush($handle); 
        flock($handle, LOCK_UN); 
        $writeContent = TRUE;
    }

    fclose($handle);
    return $writeContent;
}

Answer №1

To resolve this issue, follow these steps:

Adjust the following code snippet:

$allOutputVarPath[] = array($value => $jobRetParam[$i]);

Replace it with:

$allOutputVarPath[] = array($value => (int)$jobRetParam[$i]);

In the original version, the numbers return as strings in $_REQUEST['results']. If any arithmetic operation is performed on these strings, PHP automatically converts the string to a number.

However, when converting to JSON, the values remain as strings because JSON conversion does not recognize them as numeric data types.

Using (int) explicitly converts the string to an integer. For more information on type casting, refer to: http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

Answer №2

It appears that the issue lies in the line

$jobRetParam = $_REQUEST['results'];
. The $_REQUEST variable undergoes a process of urldecode(), causing all its components to be converted into strings rather than numbers. As a result, when you assign these strings to $allOutputVarPath, they interfere with the sorting operation within your JSON data.

To resolve this issue, you have two options: you can either utilize intval() like so

$allOutputVarPath[] = array($value => intval($jobRetParam[$i]));
or convert the string values to numbers in JavaScript before performing any sorting operations.

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

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

Getting the WebElement object by manually clicking an element while in an active WebDriver Session

I am currently developing a Java Swing application for managing object repositories in Selenium scripts. This application will launch a WebDriver instance and allow users to manually navigate to the desired element for inspection. My goal is to capture th ...

For unknown reasons, converting a string to JSONArray results in null

I'm experiencing a problem with retrieving JSON data from a URL. After converting it to a string, I attempt to convert it to a JSONArray, but it keeps returning null. The URL in question is: Here's the code snippet: public JSONArray getJsonFrom ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

AngularJS - Import and save CSV files

I have set up a nodeJS program as the server and an AngularJS web application as the client. For generating CSV files, I am utilizing the "express-csv" library (https://www.npmjs.com/package/express-csv) Below is the code for the server side: Definition ...

The dynamic union of SwiftHttp and JSONDecoder allows for seamless

When attempting to parse a json response from a server using the code snippet below: HTTP.GET(ServerPatientApi.SPLASH, parameters: nil) { response in if let error = response.error { listener.onException(error) r ...

Avoiding metacharacters and utilizing them as a string variable for selection

For example, I have a variable called myid, and its value is "abc xyz". Then, I use a function to escape metacharacters and assign the result to another variable like this: var x = "#"+escapechars(myid);. The evaluated value of x is #abc\\xyz. ...

I'm attempting to utilize a basic webcam capture upload feature, but it seems that the upload function is not functioning properly

UPDATE: This is the complete code that I simply copied and pasted. <!DOCTYPE HTML> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script language="JavaScript" type="text/javascrip ...

Tips for changing binary heap sort into d-ary heap sort:

Hey there! I have an algorithm that utilizes a binary tree for heapifying and sorting a list. I am looking to modify this sorting algorithm to work with a d-heap, d-ary heap, or k-ary heap structure instead. Here is my code: def build_heap(lista, num): ...

Having difficulty retrieving an item from a knockout observable array

When fetching data from a web API and pushing it into an observable array, I wanted to make the items in the array observable as well. Unfortunately, I found that I couldn't access the object if I made it observable. function UpdateViewModel() { ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

How to Set Up PECL Intl on MAMP 2.2 Running PHP 5.5.3

After installing the Yii2 framework, I decided to run requirements.php to check if all PHP extensions were loaded properly. To install icu4c, I used brew: brew install icu4c I also installed intl using PECL like this: /Applications/MAMP/bin/php/php5. ...

header color scheme and dimensions

Hello, I've managed to get the menu working correctly on my website at www.g-evo.com/header.php. However, I'm now facing an issue with the size of the header. I'd like to shrink the grey area slightly so it aligns better with the logo, while ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...

best practices for transferring object data to a table with ng-repeat

I have an object called 'SEG-Data with the following structure. I am attempting to display this data in a table using ng-repeat. SEG_Data Object {ImportValues: Array[2]} ImportValues: Array[2] 0: Object ImportArray: "004 ...

Break apart PDFs into individual images or convert to HTML

I'm currently working on a project that requires the development of a unique webtool. The purpose of this tool is to allow users to effortlessly upload their PDF documents, which will then be displayed in a browser with an engaging page flip effect ut ...