如何将结果动态拆分为嵌套表

时间:2016-04-27 23:08:30

标签: php mysql codeigniter

您好我无法尝试将我的数据库对象结果拆分到正确的表中以供显示。

基本上我正试图实现这个

<div class="panel"> $row->skill_group
   <table class="collapse">
     <thead> 
       <tr>
        <th>$row->name</th>
       </tr>
     </thead>
     <tbody>
       <tr>
          <td>$row->skill_name</td>
       </tr>
       <tr>
          <td> $row->competency_name </td>
    </tbody>
  </table>
</div>

可以有许多独特的技能组和许多技能名称,但每个人及其能力应该只为每种技能显示一次。

我的mysql返回正确的数据,但我无法弄清楚如何循环结果,以便我可以将它分割到嵌套在div容器中的表之间。

例如,mysql结果将是

======================================================================
| skill_group_name     | skill_name  | competency_name    | name
======================================================================
| PHP Frameworks       | Codeigniter | Working Knowledge  | User name1
| PHP Frameworks       | CakePHP     | No Knowledge       | User name1
| Database             | T-SQL       | Working Knowledge  | User name2
======================================================================

我需要将它放到上面的html结构中。

我所追求的结果是

======================================================================
 PHP Frameworks 
======================================================================
| Codeigniter | Working Knowledge  | User name1
| CakePHP     | No Knowledge       | User name1
======================================================================
 Database 
======================================================================
| T-SQL       | Working Knowledge  | User name2
======================================================================

我设法将skill_group的分组排序为:

if($row->skill_group_name != $skill_group_name)
{

    echo '<div class="panel-heading"><a href="#" data-target=".skill'.++$counter.'" data-toggle="collapse">' . $row->skill_group_name;
    $skill_group_name = $row->skill_group_name;
    echo '</a></div>';
}

但是我不知道如何为数据表本身编写循环,我该怎么做?

1 个答案:

答案 0 :(得分:1)

正如我评论的那样,我认为你应该保存到一个数组,然后implode()部分:

//Just some fake data
$array[]    =   array('PHP Frameworks','Codeigniter','Working Knowledge','User name1');
$array[]    =   array('PHP Frameworks','CakePHP','No Knowledge','User name1');
$array[]    =   array('Database','T-SQL','Working Knowledge','User name2');

// Loop through the data
foreach($array as $row) {
    // Save the table column html to array
    $section[$row[0]][] =   '<tr><td>'.$row[1].'</td><td>'.$row[2].'</td><td>'.$row[3].'</td></tr>';
}
// Loop through the section array you made
foreach($section as $title => $all) {
    // Wrap it
    echo '<div>'.$title;
    // Implode
    echo '<table>'.implode(PHP_EOL,$all).'</table>';
    echo '</div>';
}