为了账号安全,请及时绑定邮箱和手机立即绑定

使用 PHP MySQL 将数组放入 html 表

使用 PHP MySQL 将数组放入 html 表

PHP
红颜莎娜 2022-07-09 10:05:16
我在一个数据库中有 2 个表,我正在加入一个 PDO 执行,我让它以一种表的形式输出,但我需要它以另一种格式。我需要某种形式的动态支点吗?2张桌子是这样的:我希望从中得到下表:我用来整理数据的当前查询是:$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
查看完整描述

1 回答

?
茅侃侃

TA贡献1842条经验 获得超22个赞

在 $testing 中已经有了这个结构:


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

做表


<?php

    // Just to keep same variable

    $output = $testing;

?>

<table border=1>

  <thead>

    <tr>

<?php

    // We need to know wich $title has more names

    $max = 0;

    foreach($output as $title => $names) {

       if(count($names) > $max) {

          $max = count($names);

       }

?>

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

<?php } // end foreach ?>

    </tr>

    </thead>

    <tbody>

<?php

    // Loop for creating table rows

    for($i = 0; $i < $max; $i++) {

?>

    <tr>

<?php

        // Loop for creating table cells

        foreach($output as $title => $names) {

?>

        <td><?php

             // Echo only if name exists

             if(isset($names[$i]['name'])) {

                echo $names[$i]['name'];

             }

        ?></td>

<?php

        } // end foreach

?>

    </tr>

<?php

    } // end for

?>

    </tbody>

</table>


查看完整回答
反对 回复 2022-07-09
  • 1 回答
  • 0 关注
  • 162 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号