doufenpaiyu63706 2015-04-10 11:20
浏览 43
已采纳

如何在PHP中从多维数组创建html表?

I am sending a HTTP request to a Server and get a response with json format. I convert it to array using:

$response = file_get_contents($final_url);
$responseArray = json_decode($response, true);

Here is server response array($responseArray).

Array ( 
[status] => OK 
[result] => Array (
      [0] => Array
           (
             [trainno] => 12151
             [name] => SAMARSATA EXP
             [cls] => 1A 2A 3A SL
             [rundays] => F,Sa
             [from] => BQA
             [fromname] => Bankura
             [dep] => 03.45
             [to] => HWH
             [toname] => Howrah Jn
             [arr] => 08.25
             [pantry] => 0
             [type] => SUPERFAST
             [datefrom] => 10-Apr-2015
             [dateto] => 12-Apr-2020
             [traveltime] => 04.40
           )
      [1] => Array
           (
             [trainno] => 12151
             [name] => SAMARSATA EXP
             [cls] => 1A 2A 3A SL
             [rundays] => F,Sa
             [from] => BQA
             [fromname] => Bankura
             [dep] => 03.45
             [to] => HWH
             [toname] => Howrah Jn
             [arr] => 08.25
             [pantry] => 0
             [type] => SUPERFAST
             [datefrom] => 10-Apr-2015
             [dateto] => 12-Apr-2020
             [traveltime] => 04.40
           )
    )
)

Now I want to print 'result' array in html table format if [status] =>OK. How I can do it?

  • 写回答

1条回答 默认 最新

  • dongni8124 2015-04-10 11:22
    关注

    Just add an if condition, if it satisfies, then iterate the said array, pointing to proper indices:

    if($responseArray['status'] === 'OK') {
        foreach($responseArray['result'] as $result) {
            echo $result['name']; // and other indices
        }
    }
    

    Printing it into a table markup is just a creating a normal table which includes the markup.

    Super rough example:

    <?php if($responseArray['status'] === 'OK'): ?>
    <table>
        <thead>
            <tr>
            <?php foreach($headers as $h): ?>
                <th><?php echo $h; ?></th>
            <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach($responseArray['result'] as $row): ?>
            <tr>
                <?php foreach($row as $value); ?>
                    <td><?php echo $value; ?></td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调