基于CodeIgniter上的某些字段创建数据数组

时间:2017-01-24 02:20:42

标签: php codeigniter codeigniter-3

我尝试在表格中显示数组数据并且它完美无缺,但是如何根据具有主要字段name的特定字段显示数据数组是表格中数据的示例。 / p>

示例数据

  |   Name  |   Option  |   Value       
===============================
  | Ahmad   |   High    |   90
  | Smith   |   Low     |   43
  | John    |   Low     |   55
  | Adam    |   High    |   79
  | Smith   |   High    |   80
  | Adam    |   Low     |   55
  | Ahmad   |   Low     |   48
  | John    |   High    |   90

按照我预期的数据

            |       Option     |
================================            
  |   Name  |   High  |   Low  |     
===============================|
  | Ahmad   |   90    |   48   |
  | Smith   |   80    |   43   |
  | John    |   90    |   55   |
  | Adam    |   79    |   55   |

控制器

function detail_data() {            
        $data = array(
            'detail_option' => $this->my_model->model_detail($metadata_code),
        );                  
    $this->load->view('my_view', $data);
}

模型

function model_detail() {
    $query = $this->db->select('*')
                      ->from('tb_student')
                      ->group_by('name')
                      ->get();      

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $data) {
            $result_data[] = $data;
        }
        return $result_data;
    } 
}

浏览

<table>
    <thead>
    <tr>
        <td rowspan="2">Name</td>
        <td colspan="2">Option</td>
    </tr>
    <tr>
        <td>High</td>
        <td>Low</td>
    </tr>
    </thead>
    <tbody>
    <?php
        foreach ($detail_option as $row) {  
        echo '<tr>';
            echo  '<td>'.$row->name.'</td>';
            echo  '<td>'.$row->high.'</td>';
            echo  '<td>'.$row->low.'</td>'; 
        echo '</tr>';   
        }
    ?>              
    </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

控制器:

function detail_data() {            
        $data = array(
            'detail_option' => $this->my_model->model_detail()
        );                  
    $this->load->view('my_view', $data);
}

型号:

function model_detail() {
    $query = $this->db->query("SELECT * FROM `tb_student`");

    $result_data = array();

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $data) {
            $result_data[$data->Name]['Name'] = $data->Name;
            $result_data[$data->Name][$data->Option] = $data->Value;
        }
        return $result_data;
    }
}

HTML:

<table>
    <thead>
    <tr>
        <td rowspan="2">Name</td>
        <td colspan="2">Option</td>
    </tr>
    <tr>
        <td>High</td>
        <td>Low</td>
    </tr>
    </thead>
    <tbody>
    <?php
        foreach ($detail_option as $row) {  
        echo '<tr>';
            echo  '<td>'.$row['Name'].'</td>';
            echo  '<td>'.$row['High'].'</td>';
            echo  '<td>'.$row['Low'].'</td>'; 
        echo '</tr>';   
        }
    ?>              
    </tbody>
</table>

这是你想要的吗?