Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
Javascript/PHP - Reordering JSON array randomly causes null value and deletes everything

I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.

Example of my Users.json file:

[
    {
        "ID_id": "123abc",
        "ST_username": "johndoe",
        "ST_email": "j@example.com",
        "ST_fullname": "John Doe",
    },
{
        "ID_id": "def345",
        "ST_username": "sarahdoe",
        "ST_email": "s@example.com",
        "ST_fullname": "Sarah Doe",
    },
{
        "ID_id": "fgh567g",
        "ST_username": "markdoe",
        "ST_email": "mark@example.com",
        "ST_fullname": "Mark Doe",
    }

    // + additional 1000 similar items in this array
]

So, first of all, I get the JSON file's data and decode it into a PHP array:

$tableName = $_GET['tableName'];  // Lets' say $tableName is 'Users'

// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);   

Then I call this function in JS:

function reorderTableData() {
    var newOrderArray = [];
    var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
    var jsonData = JSON.parse(data_arrayStr);
    var reorderedData = JSON.stringify(jsonData, newOrderArray);
    
    $.ajax({
     url : "reorder-table-data.php",
     type: 'POST',
     data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
       success: function(data) {
       location.reload();
    
        // error
        }, error: function(e) {  
    }});
    }
}

My reorder-table-data.php code:

$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];

$data_array = json_decode($reorderedData, true);

// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);

// echo JSON object
echo json_encode($data);
?>

Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!