【问题标题】:php create dynamic html tablephp创建动态html表
【发布时间】:2011-05-20 04:54:43
【问题描述】:

我需要在解析 JSON 文件后使用 PHP 创建一个动态 html 表。
我的表需要这个列结构; Name | Status | Age | Count | Progress | Bad

如何为从 JSON 文件解析的每个“记录”创建一个新行(我可以创建一个制表符分隔的字符串)。
另一个困难是某些“记录”仅包含“名称”列的数据' 和其他所有列。

所以我的问题是如何在表格中动态添加一行并填充右列?
JSON 文件的关键形式是列标题

JSON 格式示例:

{ 
"John":     {"status":"Wait" }, 
"Jennifer": {"status":"Active" }, 
"James":    {"status":"Active","age":56,"count":10,"progress":0.0029857,"bad":0} 
}

【问题讨论】:

  • 请发布示例 JSON 文件以帮助我们帮助您。
  • 我的 JSON 文件:{ "John": { "status":"Wait" }, "Jennifer": { "status":"Active" }, "James": { "status": “活跃”,“年龄”:56,“计数”:10,“进度”:0.0029857,“坏”:0 } }

标签: php html json html-table row


【解决方案1】:

这样的事情会起作用:

$data = json_decode($json_string);
$columns = array();

echo "<table><tbody>";
foreach ($data as $name => $values) {
    echo "<tr><td>$name</td>";
    foreach ($values as $k => $v) {
        echo "<td>$v</td>";
        $columns[$k] = $k;
    }
    echo "</tr>";
}
echo "</tbody><thead><tr><th>name</th>";
foreach ($columns as $column) {
    echo "<th>$column</th>";
}
echo "</thead></table>"

【讨论】:

  • 谢谢,效果很好。添加 ';'在'回声“”'的末尾
  • 是否可以对“名称”列进行排序。我使用 sort() 尝试了几种可能性,但到目前为止都没有运气。
  • 那行不通。名称列未排序。还尝试了 asort()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2019-11-19
  • 1970-01-01
  • 2012-05-05
相关资源
最近更新 更多