dougou5852
dougou5852
2015-04-22 21:08

如何使用嵌套循环生成HTML表?

  • foreach
  • html-table
  • php
已采纳

I have a table that should look like the following:

http://hell-rider.de/Fotos/img/beispiel-1.JPG

I have the following PHP script:

foreach ($xml->result->rowset->row as $row){
    if($row{'refTypeID'} == 42){
        echo '<tr>';
        echo "<th>";
        echo $row{'date'};
        echo "</th>";
        echo "<th>";
        echo '' . $row{'ownerName1'} .'';
        echo "</th>";
        echo "<th>";
        foreach ($allgemeinxml->result->rowset->row as $type){
            echo '' . $type{'typeName'} .'';
        }
        echo "</th>";
        echo "<th>";
        echo '<p class="minus">' . $row{'amount'} .' ISK</p>';
        echo "</th>";
        echo "<th>";
        echo '<p class="kontostand">' . $row{'balance'} . ' ISK</p>';
        echo "</th>";
        echo '</tr>';
    }
}
echo "</table>";

The actual output of my script is the following, however:

http://hell-rider.de/Fotos/img/beispiel2.JPG

How do I have to change my script to populate the third column correctly (and not with MetallurgyTradeLaboratory OperationLaboratory OperationLaboratory OperationResearchCybernetics)?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqianni4080 douqianni4080 6年前

    <th> tags are for header cells, you should be using <td> data cells.

    $types = array();
    
    foreach ($allgemeinxml->result->rowset->row as $type){
        $types[] = $type{'typeName'};
    }
    
    $type_index = 0;
    
    foreach ($xml->result->rowset->row as $row){
        if($row{'refTypeID'} == 42){
            echo '<tr>';
            echo "<td>";
            echo $row{'date'};
            echo "</td>";
            echo "<td>";
            echo '' . $row{'ownerName1'} .'';
            echo "</td>";
            echo "<td>";
            echo $types[$type_index];
            echo "</td>";
            echo "<td>";
            echo '<p class="minus">' . $row{'amount'} .' ISK</p>';
            echo "</td>";
            echo "<td>";
            echo '<p class="kontostand">' . $row{'balance'} . ' ISK</p>';
            echo "</td>";
            echo '</tr>';
        }
        $type_index++;
    }
    echo "</table>";
    

    I don't know exactly what the use of if($row{'refTypeID'} == 42){ is, so you either want $type_index++; in the place I've put it above, or just above the closing brace }. For this to work well, $allgemeinxml->result->rowset->row and $xml->result->rowset->row need the same number of elements.

    点赞 评论 复制链接分享