Search code examples
phparraysloopsiteratorcycle

Iterate through two arrays, looping one continuously until the other is finished (i.e. Assign colors to menu navigation items)


O.K. Can't quite get any reference to something similar. I have two arrays, one sets my menu navigation items:

    $nav_items = array('item1_link'=>'item1_displayname',
                       'item2_link'=>'item2_displayname',
                       'item3_link'=>'item3_displayname',
                       . . .

Then, I have my second array, which sets a number of possible colors:

    $colors = array('red'=>'#f00',
                    'green'=>'#090',
                    'yellow'=>'fc0',
                    . . .

The idea is to merge these two so that the result will be:

    <a class="red" href="item1_link">item1_displayname</a>
    <a class="green" href="item2_link">item2_displayname</a>
    <a class="yellow" href="item3_link">item3_displayname</a>

The thing is: imagine I have 10 menu items and I decide on 7 different colors. The idea is that (this is where I'm stuck) a main loop will iterate through the 10 menu items, assigning to each one of the color items from a second loop, which should cycle one time and then a second time (and a third, etc., if necessary) until all items from group 1 have been exhausted. Perhaps an example of what I want to end up with will be more helpful:

    <a class="red" href="item1_link">item1_displayname</a>
    <a class="green" href="item2_link">item2_displayname</a>
    <a class="yellow" href="item3_link">item3_displayname</a>
    <a class="blue" href="item4_link">item4_displayname</a>
    <a class="orange" href="item5_link">item5_displayname</a>
    <a class="purple" href="item6_link">item6_displayname</a>
    <a class="gray" href="item7_link">item7_displayname</a>
    <a class="red" href="item8_link">item8_displayname</a> <!--Notice how colors restart here-->
    <a class="green" href="item9_link">item9_displayname</a>
    <a class="yellow" href="item10_link">item10_displayname</a>

So, PHP-code-wise, what I've got up to now is the following:

    <?php
    reset($nav_items);
    reset($colors);    

    while ((list($nav_link, $nav_name) = each($nav_items))) {
        list($color_name) = each($colors);
    ?>

    <li><a class="<?php echo $color_name ?>" href="<?php echo $nav_link ?>"><?php echo $nav_name ?></a></li>

    <?php
    }
    ?>

Which is not bad, but only goes once through color array and then repeats the last color for the remaining menu navigation items. So, how do I get the color array to restart once its iteration is finished (and the nav_item iteration is not)?? Any help on the matter will be MUCH appreciated!

P.S. I also tried this as an Iterator but couldn't quite get it to work. Perhaps that is the best response after all, but still I couldn't get the colors array to loop back in order to complete the nav_items array cycle.


Solution

  • if (current($colors) === false) reset($colors);