在水平HTML表中插入foreach输出

时间:2017-07-13 07:05:45

标签: php html arrays xml

我是一名新手,一直在寻找有关在水平 HTML 表格中插入PHP foreach输出的解决方案。在数据集 .xml文件中,有多个系列,每个系列都有24 x TIME_PERIOD和24 x OBS_VALUE作为属性。

我的问题是所有这些都被我下面编写的代码垂直(自然地)列出,我不知道如何将它们水平划分。如果你能帮助我为每个系列创建一个水平桌子,我会很高兴的。

考虑当前输出的截图:

enter image description here

代码段:

$xml=simplexml_load_file("00750006.xml") or die("Error: Cannot create object");                                                           

foreach($xml->DataSet->Series as $series) {

   foreach($series->Obs as $obs) {

           $tp = (string)$obs["TIME_PERIOD"];
           $val = (string)$obs["OBS_VALUE"];

           echo "<table><tr>

           <td class='dataC'>$tp</td>
           <td class='dataC'>$val</td>

                </tr></table>";
   } 
}

3 个答案:

答案 0 :(得分:1)

您正在为每一行创建表格。这里哪个错了。试试这个。然后指定样式以水平显示

<?php 
$xml=simplexml_load_file("00750006.xml") or die("Error: Cannot create object");                                                           

foreach($xml->DataSet->Series as $series) {
  echo "<table class='series-tbl'>";
   foreach($series->Obs as $obs) {

           $tp = (string)$obs["TIME_PERIOD"];
           $val = (string)$obs["OBS_VALUE"];

           echo "<tr>

           <td class='dataC'>$tp</td>
           <td class='dataC'>$val</td>

                </tr>";
   } 
   echo "</table>";
}
?>
<style type="text/css">
  .series-tbl
  {
    float: left;
  }
</style>

答案 1 :(得分:0)

试试这个

$xml=simplexml_load_file("00750006.xml") or die("Error: Cannot create object");                                                           
$tmp = array();
foreach($xml->DataSet->Series as $series) {
   foreach($series->Obs as $key=>$obs) {
           $tp = (string)$obs["TIME_PERIOD"];
           $val = (string)$obs["OBS_VALUE"];

           $tmp[$key] .= "<td class='dataC'>$tp</td>
           <td class='dataC'>$val</td>";
   }
}
foreach($tmp as $row){
    echo "<table><tr>";
    echo $row;
    echo "</tr></table>";
}

答案 2 :(得分:0)

只需添加行,插入新行时,请从嵌套循环中删除<table>标记。然后它会创建单独的表格。

<?php 
$xml=simplexml_load_file("00750006.xml") or die("Error: Cannot create object");                                                           

foreach($xml->DataSet->Series as $series) {

echo "<table style='float: left;'>";
foreach($series->Obs as $obs) {

       $tp = (string)$obs["TIME_PERIOD"];
       $val = (string)$obs["OBS_VALUE"];

       echo "<tr>";
       echo "<td class='dataC'>$tp</td>";
       echo "<td class='dataC'>$val</td>";
       echo "</tr>";
 } 
 echo "</table>";
}
?>