drxt70655 2015-01-04 01:33
浏览 7

JSON编码以创建表

How can I eventually put the following code into a table or viewable format.

$query = 
  "SELECT title, descr FROM details";

$result = mysqli_query($connection,$query);

$details = array();
while ($row = mysqli_fetch_assoc($result)) {
  array_push($details, $row);
}

echo json_encode($details);
  • 写回答

1条回答 默认 最新

  • dsewbh5588 2015-01-04 05:30
    关注

    No need to json encode the result, however with making tables I like to make a json template file to dictate how the table should be constructed so that I can make changes easily.

    // this would normally be located elsewhere.
    $templateJson = '"columns": {
    
        "title":{
            "title": "Title",
            "class": "title"
        },
        "descr":{
            "title": "Description",
            "class": "descr"
        }
    }';
    
    $template = json_decode($templateJson);
    
    if(is_array($details))
    {
        $markup = "<table><thead><tr>";
    
        foreach($template["columns"] as $col=>$format)
        {
            $markup .= '<th class="'.$format['class'].'">';
            $markup .= $format['title'];
            $markup .= '</th>';
        }
    
        $markup .= "</tr></thead><tbody>";  
    
        foreach($details as $i=>$row)
        {
            $markup .= '<tr>';  
            foreach($template as $col=>$format)
            {
                $markup .= '<td>'.$row[$col].'</td>';
            }
            $markup .= '</tr>';
        }
    
        $markup .= "</tbody></table>";  
    }
    
    echo $markup;
    

    I tend to do way more loops than I probably should though, there may be a more optimal way but this will give you valid table markup.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度