PHP - 将多维数组输出到HTML表中的问题

时间:2015-02-25 23:59:15

标签: php

我正在尝试编写一个PHP代码,以便在多维数组中使用示例信息,并将该信息输出到html表中。

我可以输出信息,但格式化方式是关闭的,我觉得好像有一些小问题,我需要额外的一双眼睛。

非常感谢任何帮助或建议。

我的PHP代码:

<html>

<head>
</head>

<body>

<table border="1px">

<?php

$karma_score = Array( "UserID" => Array(1,2,3,4),
                      "NameID" => Array('Doe','Smith','Chan','Zee'),
                      "Karma" => Array(45,123,1,15),
                      "LastLogin" => Array("2012-08-30","2012-09-02","2011-12-23","2012-07-01"));

    echo "<tr>";
foreach($karma_score as $key => $value){
    echo "<td>" . $key . "</td>";
}
echo "</tr>";

echo "<tr>";
foreach($karma_score as $key=> $value){
    echo "<td>";
    foreach($value as $something){
        echo $something;
    }
    echo "</td>";
}
echo "</tr>";



?>

</table>

</body>

</html>

2 个答案:

答案 0 :(得分:1)

在我的评论中,或者反过来说

<html>

<head>
</head>

<body>

<table border="1px">

<?php

$karma_score = Array( "UserID" => Array(1,2,3,4),
                      "NameID" => Array('Doe','Smith','Chan','Zee'),
                      "Karma" => Array(45,123,1,15),
                      "LastLogin" => Array("2012-08-30","2012-09-02","2011-12-23","2012-07-01"));

echo '<tr>';
foreach(array_keys($karma_score) as $head){
echo '<th>'.$head.'</th>';
}
echo '</tr>';
foreach($karma_score['UserID'] as $key=> $value){
    echo "<tr>";


        echo '<td>'.$karma_score['UserID'][$key].'</td>';
        echo '<td>'.$karma_score['NameID'][$key].'</td>';
        echo '<td>'.$karma_score['Karma'][$key].'</td>';
        echo '<td>'.$karma_score['LastLogin'][$key].'</td>';


echo "</tr>";
}




?>

</table>

</body>

</html>

演示:http://codepad.viper-7.com/ZFj6gb

答案 1 :(得分:-1)

这应该有效:

<html>
<body>
<table>
    <?php

    $karma_score = Array( "UserID" => Array(1,2,3,4),
                          "NameID" => Array('Doe','Smith','Chan','Zee'),
                          "Karma" => Array(45,123,1,15),
                          "LastLogin" => Array("2012-08-30","2012-09-02","2011-12-23","2012-07-01"));



    echo "<tr>"; 
    foreach($karma_score as $key => $value){
        echo "<th>" . $key . "</th>"; //use "th" instead for the header
    }
    echo "</tr>";

    foreach($karma_score as $key=> $value){
        echo "<tr>"; //a row for each key
        foreach($value as $something){ //foreach row print all the columns
            echo "<td>";
            echo $something;
            echo "</td>";
        }
        echo "</tr>";
    }

    ?>
</table>
</body>
</html>