Ginnani
Ginnani

Reputation: 335

how to sort files list by date

Server returns this:

<div id="urls">

   04.10.2011-some-article.html   <br />
   10.09.2011-other-article.html   <br />
   14.07.2010-some-text.html   <br />
   18.09.2011-article.html   <br />
   25.10.2011-text.html   <br />

</div>

But I'd like to sort this articles by the actual creation date. Is there any way to do it with jQuery (or immediately with php?)

please give me suggestions I appreciate your interest and help!!

Upvotes: 0

Views: 364

Answers (2)

jchook
jchook

Reputation: 7220

First-off, this is pretty bad data to be getting from the server. Looks like it might change without notice, etc. If it's from an API, you should seek a better response format such as JSON.

Nevertheless, here is some PHP that would sort your articles by date.

<?php

$serverData = <<<EOF
   04.10.2011-some-article.html   <br />
   10.09.2011-other-article.html   <br />
   14.07.2010-some-text.html   <br />
   18.09.2011-article.html   <br />
   25.10.2011-text.html   <br />
EOF;

$articles = explode("\n", $serverData);
usort($articles, function($a, $b) {
    $times = array();
    foreach (array($a, $b) as $article) {
        if ($article) {
            list($date, $title) = explode('-', trim($article), 2);
            list($day, $month, $year) = explode('.', trim($date));
            $times[] = strtotime("$year-$month-$day");
        } else {
            $times[] = 0;
        }
    }
    return $times[1] - $times[0];
});

print_r($articles);

Upvotes: 1

Jens Erat
Jens Erat

Reputation: 38672

Just do some native language compilation for this algorithm. I guess 5 or 6 lines of code should be fine.

  • strip the first two and last lines
  • use a regex to extract the date
    • either change its order to YYY-MM-DD
    • or convert to a date object
  • put these into a map (associative array)
  • final sorting is very easily done using asort

Upvotes: 1

Related Questions