Search code examples
phpjson

Json_decode display field start chronological order


How can I arrange the date (start) in chronological order when displaying a json file with several fields?

This is the json file:

{
"0": { 
"id": 1, 
"rid": 1, 
"eventType": "Rendez-vous simple", 
"title": "CONGES PAYES", 
"description": "", 
"start": "01-01-2024 00:00:00", 
"end": "06-01-2024 00:00:00", 
"color": "#000" 
}, 
"1": { 
"id": 2, 
"rid": 2, 
"eventType": "Rendez-vous simple", 
"title": "CARGILL Za 44000 MONTOIR", 
"description": "\[R\\u00e9f:6201\]", 
"start": "16-01-2024 08:00:00", 
"end": "16-01-2024 10:00:00", 
"color": "#CF00F4" 
}, 
"2": { 
"id": 3, 
"rid": 3, 
"eventType": "Rendez-vous simple", 
"title": "ADMINISTRATIF", 
"description": "", 
"start": "08-01-2024 00:00:00", 
"end": "13-01-2024 00:00:00", 
"color": "#FF8C00" 
} 
}

sort(), usort(), asort()?


Solution

  • I think you can use usort().

    Example implementation:

    <?php
    // Sample JSON data
    $json = '{ 
      "0": { "id": 1, "rid": 1, "eventType": "Rendez-vous simple", "title": "CONGES PAYES", "description": "", "start": "01-01-2024 00:00:00", "end": "06-01-2024 00:00:00", "color": "#000" },  
      "1": { "id": 2, "rid": 2, "eventType": "Rendez-vous simple", "title": "CARGILL Za 44000 MONTOIR", "description": "[R\u00e9f:6201]", "start": "16-01-2024 08:00:00", "end": "16-01-2024 10:00:00", "color": "#CF00F4" },  
      "2": { "id": 3, "rid": 3, "eventType": "Rendez-vous simple", "title": "ADMINISTRATIF", "description": "", "start": "08-01-2024 00:00:00", "end": "13-01-2024 00:00:00", "color": "#FF8C00" }
    }';
    
    // Decode JSON into an associative array
    $array = json_decode($json, true);
    
    // Function to compare the 'start' field
    usort($array, function($a, $b) {
        return strtotime($a['start']) - strtotime($b['start']);
    });
    
    echo json_encode($array); // The $array is the required sorted array.
    

    Hope this helps.