Home > Software engineering >  Print the date after each n Iterations
Print the date after each n Iterations

Time:11-08

I have two array the first one called $split, contains the number of iterations

$split = [[4,5]];
$courses = ['course 1', 'course 2', 'course 3', 'course 4', 'course 5', 'course 6', 'course 7', 'course 8', 'course 9'];

I would like to loop over my courses and print the current year for the first (4 courses), and print next year for the last 5 courses

I tried:


foreach($courses as $course){
   if($course <= $split[0][0]){
      echo date('Y').' - '. $course;
   }else{
      echo date('Y')   1.' '. $course;
   }
}

Im Expecting

  • 2022 - course 1

  • 2022 - course 2

  • 2022 - course 3

  • 2022 - course 4

  • 2023 - course 5

  • 2023 - course 6

  • 2023 - course 7

  • 2023 - course 8

  • 2023 - course 9

and so on if in case if I have more splits than 4 and 5, like

$split = [[4,4,1]]
$splits = [ [4,5], [4,4,1] ];  // as you can see is dimensional 

I'm trying to avoid nested loop

CodePudding user response:

We can get the desired output by using 3 loops

The first loop loops over $split to support multiple cases
The second loop loops over the $courses
The third loop loops over the inner value of $split

This way the 3th loop will know how much to add to the initial year, and how much we loop until it's wrapped to the next loop.

<?php

$splits = [ [4,5], [4,4,1] ];
$courses = [ 'course 1', 'course 2', 'course 3', 'course 4', 'course 5', 'course 6', 'course 7', 'course 8', 'course 9' ];
$year = date('Y');

for ($i = 0; $i < count($splits); $i  ) {

    $c = $courses;
    $split = $splits[$i];

    for ($j = 0; $j < count($split); $j  ) {
        for ($x = 0; $x < $split[$j]; $x  ) {
            echo ($year   $j) . ' - ' . array_shift($c) . PHP_EOL;
        }
    }

    if ($i !== count($splits) - 1) {
        echo " ------ "  . PHP_EOL;
    }
}

Will output:

2022 - course 1
2022 - course 2
2022 - course 3
2022 - course 4
2023 - course 5
2023 - course 6
2023 - course 7
2023 - course 8
2023 - course 9
 ------ 
2022 - course 1
2022 - course 2
2022 - course 3
2022 - course 4
2023 - course 5
2023 - course 6
2023 - course 7
2023 - course 8
2024 - course 9

As you can try by yourself in this online demo.

  •  Tags:  
  • php
  • Related