How do I create a Crosstab table with php mysql

后端 未结 3 1593
暖寄归人
暖寄归人 2021-01-06 16:58

I have the following recordset:

Date     |Role      |Name
=============================
01/02/14 |Musician  |Bob
01/02/14 |Leader    |Jerry
01/02/14 |Singer          


        
3条回答
  •  礼貌的吻别
    2021-01-06 17:10

        ';
            //initialize three arrays to hold the values
            $x_role = array();
            $y_date = array();
            $val_name = array();
            
            //store values from the database into three separate arrays NB theRole, 
            // theDate  and theName are the column names from the database
            foreach($data as $recordset)
            {
               $x_role[] =  $recordset->theRole;
               $y_date[] =  $recordset->theDate;    
               $val_name[$recordset->theRole][$recordset->theDate] = $recordset->theName;   
            }
            
            //get unique values for row and column and sort them if necessary
            $unique_x_role = array_unique($x_role);
            //asort($unique_x_role);    
            
            $unique_y_date = array_unique($y_date);
            //asort($unique_y_date);    
            
            // prints table - OUTPUT
            echo '

    '; echo '


    '; echo '

    '; echo '

    '; echo ''; echo ''; echo '';//prints 'ROLE" in upper left corner of table foreach($unique_y_date as $theDate) { echo '';//prints column headings } echo '';//closes column headings foreach($unique_x_role as $theRole) { echo ''; echo ''; //prints row title foreach($unique_y_date as $theDate) { if(isset($val_name[$theRole][$theDate]))// checks if value exists { $v = $val_name[$theRole][$theDate]; echo ''; //prints name because it exists } else { echo '';// prints a dash if no name exists } }//foreach($y_date as $theDate) echo ''; }//foreach($unique_x_role as $theRole) echo '
    ROLE'.$theDate.'
    '.$theRole.''.$v.' -
    '; echo '
    '; ?>

提交回复
热议问题