使用 PHP MySQL 将数组放入 html 表

我在一个数据库中有 2 个表,我正在加入一个 PDO 执行,我让它以一种表的形式输出,但我需要它以另一种格式。我需要某种形式的动态支点吗?

2张桌子是这样的:

http://img3.mukewang.com/62c8e2790001098205920140.jpg

我希望从中得到下表:

http://img.mukewang.com/62c8e285000165dd01260060.jpg

我用来整理数据的当前查询是:


$sql3 = $pdo->prepare('SELECT b.title, a.nameFROM poll_summary a INNER JOIN poll_answers b ON a.answers_id = b.id WHERE a.poll_id = ? ORDER BY title');

$sql3->execute([$_GET['id']]);

$testing = $sql3->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_ASSOC);    

这是它给出的示例数组:


Array ( [Knight ] => Array ( [0] => Array ( [name] => Dave ) [1] => Array ( [name] => Simon ) ) [Lieutenant ] => Array ( [0] => Array ( [name] => Tom ) ) )

我可以使用以下方法从标题列中获取表头:


<table border=1>

  <thead>

    <tr>

        <?php

            foreach($testing as $key => $val):

            ?>

                <th><?php echo $key;?></th>

             <?php endforeach; ?>

    </tr>

    </thead>

    <tbody>


        <tr>        



    </tbody>

</table>

但我不知道如何将名称值放入正确的列中。我尝试使用此代码,但无法让它按我想要的方式工作。


foreach($testing as $key => $val) {

    $arrlength = count($val);

    for($x = 0; $x < $arrlength; $x++) {

    //echo $key;


    echo $key;

    echo $val[$x]['name']; 


    }


}

输出:


Knight Dave Knight Simon Lieutenant Tom


红颜莎娜
浏览 163回答 1
1回答

茅侃侃

在 $testing 中已经有了这个结构:Array ( [Knight ] => Array ( [0] => Array ( [name] => Dave ) [1] => Array ( [name] => Simon ) ) [Lieutenant ] => Array ( [0] => Array ( [name] => Tom ) ) )做表<?php&nbsp; &nbsp; // Just to keep same variable&nbsp; &nbsp; $output = $testing;?><table border=1>&nbsp; <thead>&nbsp; &nbsp; <tr><?php&nbsp; &nbsp; // We need to know wich $title has more names&nbsp; &nbsp; $max = 0;&nbsp; &nbsp; foreach($output as $title => $names) {&nbsp; &nbsp; &nbsp; &nbsp;if(count($names) > $max) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $max = count($names);&nbsp; &nbsp; &nbsp; &nbsp;}?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th><?php echo $title;?></th><?php } // end foreach ?>&nbsp; &nbsp; </tr>&nbsp; &nbsp; </thead>&nbsp; &nbsp; <tbody><?php&nbsp; &nbsp; // Loop for creating table rows&nbsp; &nbsp; for($i = 0; $i < $max; $i++) {?>&nbsp; &nbsp; <tr><?php&nbsp; &nbsp; &nbsp; &nbsp; // Loop for creating table cells&nbsp; &nbsp; &nbsp; &nbsp; foreach($output as $title => $names) {?>&nbsp; &nbsp; &nbsp; &nbsp; <td><?php&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Echo only if name exists&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(isset($names[$i]['name'])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $names[$i]['name'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; ?></td><?php&nbsp; &nbsp; &nbsp; &nbsp; } // end foreach?>&nbsp; &nbsp; </tr><?php&nbsp; &nbsp; } // end for?>&nbsp; &nbsp; </tbody></table>
打开App,查看更多内容
随时随地看视频慕课网APP