rob.m rob.m - 19 days ago 5
PHP Question

How to display a years list ordered by century

I have an array of years like this:

[1500, 1946, 1923, 1258]


and I'd like to display them ordered by century (displaying the corresponding century as well) this way:

<ul>
<li>1200
<ul>
<li>1258</li>
</ul>
</li>
<li>1500</li>
<li>1900
<ul>
<li>1923</li>
<li>1946</li>
</ul>
</li>
</ul>


Note that years of the same century are children of the same
il
century item. Also, if one of the years matches with the century itself, I only want to display the parent
il
.

My idea was to use a range but how do I check if the value is more or less than the current range and nest a
ul
or
li
correctly based on the year? - Not even sure if it's the correct approach tho, this below isn't fully working but it's an idea:

<ul>
<?php
$value_1 = "1942";
$value_2 = "1230";
foreach (range(0, 3000, 1000) as $number) {
echo $value;
if ($value < $number) { ?>
<li>
<?php echo $value... ?>
</li>
<?php } ?>
<?php } ?>
</ul>


I'll put it in plain words:

I have a cms where the user can select a year, could be 1942 or 1230. Now i get these years in front end and I would like to build a dynamic navigation out of them as per the html above

Answer

Here you have another way to do that. This works also if there are more than one year in the same century.

<?php

$yearsArray = [1500, 1946, 1923, 1258];
$centuryHash = [];

$yearsArray = array_unique($yearsArray);
sort($yearsArray);

foreach ($yearsArray as $year) {

    $currentCentury = floor($year/100)*100;

    if(!$centuryHash[$currentCentury]){
        $centuryHash[$currentCentury] = [];
    }

    if($currentCentury != $year){
        $centuryHash[$currentCentury][] = $year;
    }
}

//echo "<pre>" . print_r($centuryHash,1) . "</pre>";

echo "<ul>";

foreach ($centuryHash as $century => $centuryYears) {
    echo "<li>" . $century;

    if($centuryYears){
        echo "<ul>";

        foreach ($centuryYears as $year) {
            echo "<li>$year</li>";
        }

        echo "</ul>";
    }

    echo "</li>";
}

echo "</ul>";

Here you can see the content of $centuryHash:

Array
(
    [1200] => Array
        (
            [0] => 1258
        )

    [1500] => Array
        (
        )

    [1900] => Array
        (
            [0] => 1923
            [1] => 1946
        )

)

And here you can see the result:

  • 1200
    • 1258
  • 1500
  • 1900
    • 1923
    • 1946