Skip to content
PHP Logo

How can PHP be used to sort data from a text database by date?

To sort data from a text database by date using PHP, you can read the data from the text file into an array, parse the dates, and then use a sorting function to sort the array based on the dates. Finally, you can output the sorted data.

php
<?php
// Read data from text file into an array
$data = file('data.txt', FILE_IGNORE_NEW_LINES);

// Parse dates and sort data by date
usort($data, function($a, $b) {
    $dateA = strtotime(explode(',', $a)[1]);
    $dateB = strtotime(explode(',', $b)[1]);
    return $dateA - $dateB;
});

// Output sorted data
foreach ($data as $line) {
    echo $line . "\n";
}
?>