数组变量不在while循环中打印出来

时间:2019-02-21 08:24:09

标签: php arrays

我要在while循环外初始化一个数组变量,问题是,当从while循环中打印该数组变量时,则不显示数组,而在循环中打印此数组变量时,则显示数组。

>
<?php 
  $all_rollno="";
  //Get Current Session
  $Res_Sess = mysql_query("SELECT sessionid from tbl_session where status=1 ORDER BY sessionid desc limit 1");
  $Row_Sess = mysql_fetch_array($Res_Sess);
  $Session = $Row_Sess[0];

 //Get Batch
 $Res_Bat = mysql_query("SELECT batchid,batchname,code FROM tbl_batch where status=1 and batchid!=12 ORDER BY batchid asc");

 while($Row_Bat = mysql_fetch_array($Res_Bat)){
     $Batch = $Row_Bat['batchid'];
     $Bat_Code = $Row_Bat['code'];

     //Present - Attendance
     $Patt4 = mysql_query("select count(id),rollno from tbl_attendance where batchid = '$Batch' and sessionid = '$Session' and attend = 1 GROUP by rollno");

     $arraytpresent="";
     $array_rollno="";
     $ipresent=0;
     while($Row_P4 = mysql_fetch_array($Patt4)){
        $arraytpresent[$ipresent] = round(($Row_P4[0]/$maxValue*100),0);
        $array_rollno[$ipresent] = $Row_P4[1];
        $ipresent++;
     }
     if(sizeof($all_rollno)>0){
         $all_rollno = array_merge($all_rollno,$array_rollno);
     } else {
         $all_rollno = $array_rollno;
    }
    //print_r($all_rollno);
}
print_r($all_rollno);

3 个答案:

答案 0 :(得分:6)

在下面的代码中,我做了4次更改:

<?php
  $all_rollno=array(); // 1. changed it to array

  // get the session
  $Res_Sess = mysql_query("SELECT sessionid from tbl_session where status=1 ORDER BY sessionid desc limit 1");
  $Row_Sess = mysql_fetch_array($Res_Sess);
  $Session = $Row_Sess[0];

  // get the list of badges
 $Res_Bat = mysql_query("SELECT batchid,batchname,code FROM tbl_batch where status=1 and batchid!=12 ORDER BY batchid asc");

 // loop and get the total attendance
 while($Row_Bat = mysql_fetch_array($Res_Bat)){
     $Batch = $Row_Bat['batchid'];
     $Bat_Code = $Row_Bat['code'];

     $Patt4 = mysql_query("select count(id),rollno from tbl_attendance where batchid = '$Batch' and sessionid = '$Session' and attend = 1 GROUP by rollno");

     $arraytpresent=array(); // 2. changed it to array
     $array_rollno=array(); // 3. changed it to array
     $ipresent=0;
     while($Row_P4 = mysql_fetch_array($Patt4)){
        $arraytpresent[$ipresent] = round(($Row_P4[0]/$maxValue*100),0);
        $array_rollno[$ipresent] = $Row_P4[1];
        $ipresent++;
     }

     // merge the data
     $all_rollno = array_merge($all_rollno,$array_rollno); // 4.Merge with the array no need for the if condition.
}
print_r($all_rollno);

请注意,不建议使用mysql,请改用mysqli / PDO。

答案 1 :(得分:0)

您的$array_rollno应该定义为一个空数组而不是字符串:

$array_rollno = [];

答案 2 :(得分:0)

只需更改您的第一行,它将起作用。

$all_rollno=[];

$all_rollno="";会将变量初始化为字符串而不是数组,因此请使用上述语法更改此行。