亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 163 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號