rob.m rob.m - 13 days ago 6
PHP Question

How to check a value against current range in foreach?

I need to check if the value I print out of a variable is within one rage or the other in order to be able to build a dynamic navigation like:

<ul>
<li>1200
<ul>
<li>1230</li>
</ul>
</li>
<li>1900
<ul>
<li>1942</li>
</ul>
</li>
</ul>


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 = [1942, 1923, 1230];
$centuryHash = [];

sort($yearsArray);

foreach ($yearsArray as $year) {
    $currentCentury = round($year, -2);

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

    $centuryHash[$currentCentury][] = $year;
}

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

// Now we go through $centuryHash and print it the way we want

echo "<ul>";

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

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

    echo "</ul></li>";
}

echo "</ul>";

Here you can see the content of $centuryHash:

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

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

)
Comments