在PHP中使用foreach进行组合

时间:2017-10-25 19:20:30

标签: php html mysql foreach while-loop

我已经工作了一段时间来组合一个" foreach循环"和#34; while循环"。我希望我的foreach跑30次。这由 $ counter 表示。现在的问题是我的"而#34;再次启动" foreach"每次。但它听到30次转动"而#34;每一次。

如果我将while部分拿走并使用静态代码,它将完全正常工作。但我需要链接我的数据库以获取信息。也许一个选择是做一个" foreach" a" for"或者完全不同的选择。但我不知道如何安排他。

$ counter =一个月内的天数

$ index =正常运行时间。 Max $ counter

$ NUM = 1人的唯一身份

$ index和$ cut_startday一起表明一个方框是红色还是绿色。

这里是无法工作的代码:

 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*/ }   

代码的想法是什么。我想要一个日历,一个月的顶行日期和左侧的人们。如果核心在天和1个人之间找到匹配,如果不是绿色,则将td红色着色。

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以将foreach语句更改为for ($index = 0; $index < 30; $index++)。为了改进你的代码我建议把for循环放在while循环中。这样,您只需查询一次数据库而不是30次。