dongqiongzheng0615 2017-03-29 06:33
浏览 24
已采纳

如何从列到底显示表格?

I have array:

$array = [
    'category1' => [
        'product33',
        'product41'
    ], 
    'category2' => [
        'product1',
        'product45'
    ], 
    'category3' => [
        'product65',
        'product23',
        'product423'
    ], 
];

How can I show this data from array in table from top to bottom?

This should looks this:

category1  | category 2 | category3
product33  | product1   | product65
product41  | product45  | product23
           |            | product423

I tried:

<table>
  <tr>
     <?php foreach ($array as $category): ?>
         <td><?php echo $category ?></td>
     <?php endforeach ?>
  </tr>
//????
</table>
  • 写回答

3条回答 默认 最新

  • dou31797719 2017-03-29 06:54
    关注

    I think your question is very similar to this

    First calculate the $max_products. Then print header (category1, category2, etc). Then in nested loop print elements in rows to $max_products (you need to check if that category has element with index $i ofc).

    $max_products = 0;
    
    foreach($array as $category => $products){
    
        $current = count($products);
    
        if($current > $max_products){
            $max_products = $current;
        }
    }?>
    
    <table>
        <thead>
            <tr>
                <?php
                    foreach( $array as $category => $products ){
                        echo "<th>$category</th>";
                    }
                ?>
            </tr>
        </thead>
        <tbody>
    
            <?php for( $i = 0; $i < $max_products; $i++ ){ ?>
            <tr>
    
                <?php
                    foreach( $array as $category => $products ){
    
                        if( $products[$i] ){
                            echo "<td>$products[$i]</td>";
                        } else {
                            echo "<td>&nbsp;</td>";
                        }
    
                    }
                ?>
    
            </tr>
            <?php } ?>
    
        </tbody>
    </table>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan