用于循环变量的PHP函数

时间:2015-01-12 06:33:28

标签: php function foreach

我有这个编码:

foreach ($users_id_array[REGION_NORTH_REFID][813] as $key) {

        $query_course = "SELECT ut_lp_marks.obj_id, object_data.title, read_event.spent_seconds, " .
                "read_event.read_count, ut_lp_marks.status, ut_lp_marks.percentage, ut_lp_marks.u_comment FROM ut_lp_marks ".
                "LEFT JOIN object_data ON (object_data.obj_id = ut_lp_marks.obj_id) ".
                "LEFT JOIN read_event ON (read_event.obj_id = object_data.obj_id AND read_event.usr_id = ut_lp_marks.usr_id) ".
                "WHERE ut_lp_marks.usr_id=$key AND object_data.type = 'crs'";

             $set_course = mysql_query($query_course);

                    while($rec_course = mysql_fetch_assoc($set_course))
                    {

                           if ($rec_course['status'] == 0) {

                                $total_regna++;
                            }
                            if ($rec_course['status'] == 1) {
                                $total_reginprogress++; 
                            }
                            if ($rec_course['status'] == 2) {
                                $total_regpassed++;
                            }
                            if ($rec_course['status'] == 3) {
                                $total_regfailed++;
                            }       

                           // $total_attempt = $total_attempt + $rec_course['read_count'];                                                            
                           // $total_spent = $total_spent + $rec_course['spent_seconds']; 


                    }
                    $no_test++;
            }   

我使用的变量是每个:

813, 945, 835, 777 

我的问题是我现在的编码仅适用于1个变量 如何为不同的变量使用相同的代码,我需要制作数组还是函数?
如果我使用1个代码,我如何访问...不同的 $total_regna++; $total_reginprogress++; $total_regpassed++; $total_regfailed++; 对于4变量?..

2 个答案:

答案 0 :(得分:2)

您可以创建这些值的数组,例如

$values = array('813','945','835','777');

而不是为每个使用,您可以在查询中内爆此数组值。

$query_course = "SELECT ut_lp_marks.obj_id, object_data.title, read_event.spent_seconds, " .
            "read_event.read_count, ut_lp_marks.status, ut_lp_marks.percentage, ut_lp_marks.u_comment FROM ut_lp_marks ".
            "LEFT JOIN object_data ON (object_data.obj_id = ut_lp_marks.obj_id) ".
            "LEFT JOIN read_event ON (read_event.obj_id = object_data.obj_id AND read_event.usr_id = ut_lp_marks.usr_id) ".
            "WHERE ut_lp_marks.usr_id in (".implode(',',$values).") AND object_data.type = 'crs'";

现在while循环是一样的。

我认为这样做会很好。

答案 1 :(得分:0)

$ids=array(813, 945, 835, 777);
for ($i=0;$i<4;$i++){
   foreach ($users_id_array[REGION_NORTH_REFID][$ids[$i]] as $key) {
...