• Jetzt anmelden. Es dauert nur 2 Minuten und ist kostenlos!

Array nach Datum sortieren

Sylnois

Mitglied
Hallo Leute

Ich brauche eure Hilfe. Ich möchte gerne alle meine Newsletter verlinken.
Da ich faul bin, möchte ich das gerne mit PHP lösen.
Die Darstellung sollte so aussehen:

2013

Januar
Februar
März
..
..

2012

Januar
Februar
März
..
..

Ich habe nun HTML-Files welche sich so nennen: <company>_Newsletter_<month>_<year>.html
Wie kann ich diese nun am besten sortieren und verlinken(siehe obige Darstellung).

Mein bisheriger Code:
PHP:
<?php
    $filePath =$PATH.'/var/www/test/newsletter/';    $dir = opendir($filePath);    $i = 0;    while($file = readdir($dir)){        list($company, $subject, $month, $year) = split("_", $file);        ?>        <h2><?php echo $year ?></h2>        <a href="newsletter/<?php echo $file ?>" target="_blank"><?php echo $month ?></a>        <?php        echo"<br>";    }?>

Gruss
Sylnois
 
Zum Beispiel:

PHP:
<?php

function monthToName($n)
{
    $names = array('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli',
        'August', 'September', 'Oktober', 'November', 'Dezember');

    return $names[$n - 1];
}

error_reporting(-1);
ini_set('display_errors', 1);

$path = './newsletters';

$dir = opendir($path);
rewinddir($dir);

$items = array();

while (($file = readdir($dir)) !== false) {
    if ($file === '.' || $file === '..') {
        continue;
    }

    list($company, $subject, $month, $year) = explode('_', $file);

    $month = (int) $month;
    $year  = (int) $year;

    if (!isset($items[$year])) {
        $items[$year] = array();
    }

    if (!isset($items[$year][$month])) {
        $items[$year][$month] = array();
    }

    $items[$year][$month][] = array(
        'company' => $company, 'subject' => $subject, 'file' => $file);
}

closedir($dir);

krsort($items);

$itemsYear = null;
foreach ($items as &$itemsYear) {
    ksort($itemsYear);
}
unset($itemsYear);

?>

<?php foreach ($items as $year => $itemsYear) : ?>

<h2><?php echo $year ?></h2>

<?php foreach ($itemsYear as $month => $itemsMonth) : ?>

<h3><?php echo monthToName($month) ?></h3>

<?php foreach ($itemsMonth as $item) : ?>

<p><a href="newsletter/<?php echo $item['file']; ?>" target="_blank"><?php echo $item['company']; ?></a></p>

<?php endforeach; ?>
<?php endforeach; ?>
<?php endforeach; ?>
 
Zurück
Oben