Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda