Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Prevent repeating nested foreach multidimensional array

I have been trying to loop nested foreach loops but the problem is first foreach loop records repeating as the count of second foreach loop first array is coming from mysql data and second array I have wrote below, In my case i want to loop the color presets in second array with first foreach loop results. I'm not much good in arrays please help me to solve this issue. here is the second array and code :

$colors = array ( 
        0 => array ("id"=> 0, "dark" => "#16a085", "light" => "#1ABC9C"),
        1 => array ("id"=> 1, "dark" => "#2980B9", "light" => "#3498DB "),
 );
$unique = array_unique($colors, SORT_REGULAR);
          foreach ($skill as $skilldata) {
                 foreach ($unique as $key => $val) {

  <div class="skillbar clearfix " data-percent="<?php echo $skilldata['js_skill_perc'].'%'; ?>">
    <div class="skillbar-title" style="background: <?php echo $val['dark']?>;">
    <span><?php echo $skilldata['js_skill_title']; ?></span></div>
    <div class="skillbar-bar" style="background-color: <?php echo $val['light']?>; width: <?php echo $skilldata['js_skill_perc'].'%'; ?>;"></div>
    <div class="skill-bar-percent"><?php echo $skilldata['js_skill_perc'].'%'; ?></div>
 </div>

<?php }} ?>

Output should be like : HTML5 (green) PHP(blue) and SEO (green) but this is how output looks like:

enter image description here

like image 631
Sahan Perera Avatar asked Dec 21 '25 01:12

Sahan Perera


1 Answers

If You need to just switch the colors from line to line, You can use CSS for this (see :nth-child(even) and :nth-child(odd)) or do it in PHP like this:

$colors = array(
    ...
);
$colors_count = count($colors);
$colors_index = 0;
foreach ($skill as $skilldata) {

    $color = $colors[$colors_index % $colors_count];
    $colors_index++;

    echo ... whatever using $color ...
}
like image 199
Roman Hocke Avatar answered Dec 22 '25 17:12

Roman Hocke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!