缩短“for / switch-case”

时间:2010-08-04 17:49:47

标签: php switch-statement

学校系统有30所学校。最低的学校代码是298,最高的是516.对于每所学校,将调用相同的流程。我到目前为止采用的方法可以在下面看到。如何缩短此代码?谢谢。

for ( $i = 298; $i <= 516; $i++ )
{
   switch ( $i )
   {
      case 298:
         $c_sch = strval ( $i ) ;
         // call a function
         uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3,
                            $d_year, $d_datadate ) ;
      case 303:
         // etc....etc.....
      case 309:
         // etc....etc.....
      default:
   }
}

3 个答案:

答案 0 :(得分:11)

不确定我理解。是switch,因为298和516之间的某些ID不存在吗?

在这种情况下,我更喜欢

$school_ids = array(
  298, 300, 304, 312, 319, 320, 321, ....... all school IDs that actually exist
);

foreach (school_ids as $school) // a list of all IDs that exist
{
  $c_sch = strval ( $school ) ;
  uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3, d_year, $d_datadate);
}

答案 1 :(得分:2)

$schoolCodes = array(304, 313 /* etc */ );
foreach($schoolCodes as $code {
     $c_sch = strval ( $code ) ;
     // call a function
     uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3,
                        $d_year, $d_datadate ) ;
}

这是你的意思吗?

答案 2 :(得分:2)

制作一系列学校代码:

$schoolCodes =  array( 298, 303, 309 ...... );
foreach( $schoolCodes as $code ) {
    $c_sch = strval ( $i ) ;
    uf_mem_requester ( $c_sch, $t_mem1, $t_mem2, $t_mem3, $d_year, $d_datadate ) ;
    //and so forth...
}

这与迭代代码具有完全相同的效果,但它更有效,因为您不需要遍历任何您不需要的值,并且更容易通过通过的数组更新代码条件句。 :d