【问题标题】:json to html table in php/javascriptjson 到 php/javascript 中的 html 表
【发布时间】:2014-03-11 15:25:01
【问题描述】:

我有一个这样的 json 文件:

{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
},

我需要在这样的表格中显示它:

<table>
            <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>
</table>

我如何在 PHP 或 javascript 中做到这一点?

非常感谢大家 ;)

【问题讨论】:

  • 它是您提供的对象而不是 json。
  • 您提供的文件内容确实是json。
  • 你能帮我把它展示在桌子上吗?谢谢
  • 你想在 td 中显示对象的值吗,比如"28-02-2014""Servicash - Equipamentos Electrónicos, Lda.""Banco de Portugal",如果我错了,请纠正我。

标签: javascript php json


【解决方案1】:

以下是您可以在 PHP 中执行此操作的方法:

$json=file_get_contents("http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)");
$data =  json_decode($json);

//var_dump($data);
echo "<table>
           <tr>
                <td><strong>Data de publicação</strong></td>
                <td><strong>Empresa Contratada</strong></td>
                <td><strong>Empresa que Contratou</strong></td>
                <td><strong>ID</strong></td>
                <td><strong>Objecto adquirido</strong></td>
                <td><strong>Preço Contratual</strong></td>
                <td><strong>Data do Contrato</strong></td>
            </tr>";

foreach($data as $object):?>

           <tr>
                <td><strong><?php echo $object->{'publicationDate'}?></strong></td>
                <td><strong><?php echo $object->{'contracted'}?></strong></td>
                <td><strong><?php echo $object->{'contracting'}?></strong></td>
                <td><strong><?php echo $object->{'id'}?></strong></td>
                <td><strong><?php echo $object->{'objectBriefDescription'}?></strong></td>
                <td><strong><?php echo $object->{'initialContractualPrice'}?></strong></td>
                <td><strong><?php echo $object->{'signingDate'}?></strong></td>
            </tr>

<?php endforeach;
      echo "</table>";
?>

DEMO

【讨论】:

  • $json 是什么变量?我不明白对不起
  • @user3332475 $json=file_get_contents("base.gov.pt/base2/rest/…); 抱歉我更新了
  • 而变量 $object 是什么?...对不起,我是 php 新手
  • 因为我这样做并显示此错误:警告:在第 27 行的 C:\xampp\htdocs\base2\index.php 中为 foreach() 提供的参数无效
  • 你必须在网络服务器上运行它。
【解决方案2】:

这是一个 JSFiddle,它展示了如何在您的对象中打印数据:

http://jsfiddle.net/4PVr5/1/

还有代码:

HTML

<table id="table">
    <tr>

    </tr>
</table>

JAVASCRIPT

var object = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};
for (var prop in object) {
      // important check that this is objects own property 
      // not from prototype prop inherited
      if(object.hasOwnProperty(prop)){
          var td = document.createElement("td");
          var strong = document.createElement("strong");
          var text = document.createTextNode(prop + " - " + object[prop]);
          strong.appendChild(text);
          td.appendChild(strong);
          document.getElementById("table").appendChild(td);
      }
   }

编辑更新到 angus_thermopylae:

我已经更新了 JSFiddle 来展示这个概念:http://jsfiddle.net/4PVr5/12/

然后,您可以在对象上拥有任意数量的属性,但只打印您定义的属性并按照您定义的顺序。您只需添加一个文本字符串,然后您就会得到另一个打印。

编辑更新: 我更新了代码以遵循表格标题。现在它直接添加它们并且还处理属性太少的对象。

HTML

<table id="table">
    <thead>
        <th id="publicationDate"></th>
        <th id="contracted"></th>
        <th id="contracting"></th>
        <th id="id"></th>
        <th id="objectBriefDescription"></th>
        <th id="initialContractualPrice"></th>
        <th id="signingDate"></th>
    </thead>
    <tbody>

    </tbody>
</table>

JAVASCRIPT

var orderedObject = {
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014"
};

var unorderedObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

var toManyPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    signingDate: "28-02-2014",
    publicationDate: "28-02-2014",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
    newProp: "ignored",
    newProp1: "ignored",
    newProp2: "ignored",
};


var toFewPropertiesObject = {
    id: 994738,
    objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
    initialContractualPrice: "12.945,50 €",
    contracted: "Servicash - Equipamentos Electrónicos, Lda.",
    contracting: "Banco de Portugal",
};

printObjectInTable(orderedObject, "table");
printObjectInTable(unorderedObject, "table");
printObjectInTable(toManyPropertiesObject, "table");
printObjectInTable(toFewPropertiesObject, "table");

function printObjectInTable(objectToIterate, tableID) {
    var thChildren = document.getElementById(tableID).getElementsByTagName("th"),
        childrenLength = thChildren.length,
        tr = document.createElement("tr");
    for (var i = 0; i < thChildren.length; i++) {
        var th = thChildren[i];
        // important check that this is objects own property 
        // not from prototype prop inherited
        var td = document.createElement("td");
        if (objectToIterate.hasOwnProperty(th.id)) {
            td.appendChild(document.createTextNode(objectToIterate[th.id]));
        }
        tr.appendChild(td);
    }
    document.getElementById(tableID).getElementsByTagName("tbody")[0].appendChild(tr);
}

【讨论】:

  • 我实际上更喜欢您的解决方案——更通用。假设对象来自另一个来源,您将如何确保属性的顺序是正确的? (或者,如果他们添加了一个属性,那么表格不会失衡?)
  • 您可以添加一个方法来检查它有多少属性。并根据属性名称向表添加排序。之后运行对象并插入 TD。希望这是有道理的。
  • 确实如此——对于这些类型的制表,我通常在我的解决方案中制作一个版本,但我一直在寻找概括的方法。这样可以减少返工。
  • @angus_thermopylae 看到更新的答案和小提琴。
  • 非常好!我在想你需要一个属性列表,但我没有使用这种获取单个属性的方法(知道它,从来没有真正需要它)。我敢打赌,如果您传入属性名称数组,您可以在整个 Web 应用程序中为一堆不同的表重用它。
【解决方案3】:

每行转换将像这样工作(低级别,不做任何花哨的事情):

//with jdata as the object below
{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 €",
signingDate: "28-02-2014"
}

function tablize(jdata) {
    var trow = "<tr>";
    trow += "<td>"+jdata.publicationData+"</td>";
    trow += "<td>"+jdata.contracted+"</td>";
    trow += "<td>"+jdata.contracting+"</td>";
    trow += "<td>"+jdata.id+"</td>";
    trow += "<td>"+jdata.objectBriefDescription+"</td>";
    trow += "<td>"+jdata.initialContractualPrice+"</td>";
    trow += "<td>"+jdata.signingDate+"</td>";
    trow += "</tr>"
    return trow;
}

现在你的问题是把它放在桌子上。假设您有能力(稍微)调整表格结构,我建议您像这样设置表格:

<table>
    <thead>
        <tr>
            <th><strong>Data de publicação</strong></th>
            <th><strong>Empresa Contratada</strong></th>
            <th><strong>Empresa que Contratou</strong></th>
            <th><strong>ID</strong></th>
            <th><strong>Objecto adquirido</strong></th>
            <th><strong>Preço Contratual</strong></th>
            <th><strong>Data do Contrato</strong></th>
        </tr>
    </thead>
    <tbody id="cdata"></tbody>
</table>

然后,您只需要一个函数来遍历所有数据并添加累积的行,或者将新创建的行附加到元素:

假设您将这些数据作为数组获取:

function fillTable(contractarray) {
    var tblrows = "";
    if (contractarray) {
        for (var i=0;i<contractarray.length;i++) {
            tblrows += tablize(contractarray[i]);
        }
    }
    //appropriate method to set the table body--using jQuery for brevity
    $("#cdata").html(tblrows);
}

如果您没有能够调整表格 html,那么您将不得不以另一种方式在 DOM 结构中“找到”表格并重新创建整个内容(包括标题) 或通过适当地清除/添加行来调整它。

无论哪种方式,tablize(jdata) 函数都可以工作,第二个函数需要相应调整。

完全提取它(使用请求者提供的网址:

var dataurl = "http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)";

$.getJSON(dataurl, function(data) { tablize(data)});

这会启动请求,将数据传递给 tablize() 函数,然后填充行。一个小(但很好)的副作用是,如果没有返回数据,表就会清空,表明我们什么也没有返回。

【讨论】:

  • 我只需要在 php 文件中工作,因为 json 文件有很多数据
  • 就是这样的json文件:
  • 这里有很多好的可能性——这主要取决于您对 javascript 的熟悉程度,以及您是想在客户端还是服务器端工作。
  • 我只是在本地主机上进行测试
  • 对不起——“客户端”是指让用户的浏览器完成所有工作,“服务器端”是指让 php 传递已经格式化的数据。
【解决方案4】:

根据您对评论的回答,您正在使用

$('table#tbl TBODY').append(

用于将数据追加到表中,

但你应该使用

$('table#tbl').append(

其他代码没问题

您还必须将代码运行到网络服务器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2020-05-27
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多