Jesse Lafeber
Jesse Lafeber

Reputation: 21

Combining while in foreach in PHP

I have been working for a while to combine a "foreach loop" and a "while loop". I would like my foreach to run 30 times. This is indicated by $counter. Now the problem is that my "while" again starts the "foreach" every time. But it hears 30 times turning the "while" each time again.

If I get the while part away and use static code, it will work completely. But I need to link my DB for the information. Perhaps an option is to make a "foreach" a "for" or a whole different option. But I have no idea how to set him up.

$counter = days in a month

$index = foreach time for running. Max $counter

$NUM = unique number of 1 people

The $ index together with $ cut_startday together indicate when a box is to be red or green.

Here's the code for the none working foreach:

 foreach(range(1,$counter) as $index) {/*open foreach*/
                       $get_data = "
                            SELECT * 
                            FROM core";



    $result1 = $conn->query($get_data) or die($conn ->error);


    //Start query 1
    if($result1) {
                    while($row = $result1->fetch_assoc()) {


            // Get NUM, START DATE and END DATE
            $NUM = ($row['c_m_num']);
            $startdate = ($row['e_date_s']);
            $enddate = ($row['e_date_e']);

            // Cut strings for date
            $sort_year = substr($startdate, 6, 4); // START YEAR -> 2017
            $sort_month = substr($startdate, 0, 2); // START MONTH -> 09
            $cut_startday = substr($startdate, 3, 2); // START DAY -> 17
            $cut_endday = substr($enddate, 3, 2); // END DAY -> 19



                         if($load_m_NUM == "$NUM" and $index >= $cut_startday && $index <= $cut_endday ){
                            echo"<td style='background-color:red;'>x</td>";
                            }


                            else{
                    echo"<td style='background-color:green;'></td>";
                    }


        }

        }           



/*end foreach*/ }   

What the idea is of the code. I want a calendar with a top row de days of a month and on the left side al the people. If the core find a match between days and 1 men, color the td red if not color green.

Any help greatly appreciated!

Upvotes: 2

Views: 268

Answers (1)

Jonas &#196;ppelgran
Jonas &#196;ppelgran

Reputation: 2747

You could change the foreach statement to for ($index = 0; $index < 30; $index++). To improve your code I suggest putting the for loop inside the while loop instead. That way you only query the database once instead of 30 times.

Upvotes: 1

Related Questions