3

我有以下代码。我有一个月的数组。

         $m="";
         $months = array(1=>'January',2=>'February',3=>'March',4=>'April',5=>'May',6=>'June',7=>'July',8=>'August',9=>'September',10=>'October',11=>'November',12=>'December');

         foreach($objhst_fees->fetch_hst_fees("`month`,`fees`","where `grno`='".$stu_name['grno']."'")as $count_month)
          { 
                           //value like:$count_month['month']=1,2,3
            $m  .= $count_month['month'].",";
          }

所以假设 $m=1,2,3,4,5,
然后,我将其分解并创建数组。

          $paid_month = explode(",",$m);
          $arr=array();
          foreach($paid_month as $key=>$p)
          {
            array_push($arr,$p);
          } 

然后,我打印不在$arr.

          foreach($months as $key=>$a)
          {
             if(!in_array($key,$arr))
             {
                echo $a.",";
                //echo $months[$key];
             }
           }

但我认为,这种方法是渴望它。那么这样做的替代方法是什么?

4

3 回答 3

0

在代码中:

foreach($objhst_fees->fetch_hst_fees("`month`,`fees`","where `grno`='".$stu_name['grno']."'")as $count_month) { 
   //value like:$count_month['month']=1,2,3
   $m  .= $count_month['month'].",";
}

你可以改变:

$m  .= $count_month['month'].",";

$m[] = $count_month['month'];

这将避免需要再次explode()

于 2013-10-22T10:27:06.967 回答
0

尝试这个:

$m = array();
$months = array('', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

foreach( $objhst_fees->fetch_hst_fees("`month`,`fees`","where `grno`='".$stu_name['grno']."'")as $count_month)
{
    $m[] = $count_month['month'];
}

foreach ($months as $key => $month) {
    if (in_array($key, $m)) {
        continue;
    }

    echo $month . ',';
}

您不需要将 $m 连接为字符串然后将其分解。还要注意我的数组
有一个小的变化。$months我取下了钥匙。但是为了保留它们从1值开始,我只是在第一个(零)位置添加了一个空值。

于 2013-10-22T10:27:33.717 回答
0

像这样的东西?

$paid_month = explode(",", $m);
$paid_months = array();
foreach($paid_month as $p) 
{
    $paid_months[$p] = (isset($months[$p]) ? $months[$p] : 'Unknown');
}
print_r($paid_months);
于 2013-10-22T10:28:19.707 回答