Essetee's Website

Sort a json file on a specific field

<?php
$PATH = "PATH_TO_YOUR_JSON-FILE";

// Load the JSON file
$json = file_get_contents('$PATH/data.json');

// Decode the JSON file to a PHP-array
$data = json_decode($json, true);

// Sort the array on the filed 'field_name'
usort($data, function ($a, $b) {
    return strcmp($a['naam'], $b['naam']);
});

// Encode back JSON
$sortedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// write the result to a new json file
file_put_contents('$PATH/sorted-data.json', $sortedJson);

echo "The sorted JSON file is saved as 'sorted-data.json'.\n";
?>