关联数组并用foreach语句表显示结果

这是我的代码并且工作正常但是当我显示 foreach 语句时它搞砸了!


$people= array(


array(

    "name" => "Jennifer Kimbers",

    "email" => "abc@gmail.com",

    "city" => "Seattle",

    "state" => "Washington"),


array(

    "name" => "Rodney Hutchers",

    "email" => "def@gmail.com",

    "city" => "Los Angeles",

    "state" => "California"),


);



    echo "<table>";

    echo "<th>FullName</th>";

    echo "<th>Email</th>";

    echo "<th>City</th>";

    echo "<th>State</th>";


foreach ($people as $person)

{

    foreach ($person as $key=>$values)

    {

    echo "<tr>";

    echo "<td>$values</td>";

    echo "</tr>";


    }

}

我的问题是如何使用 foreach 语句显示组织的结果,例如:<th>Fullname<th>下面只有名称Jennifer Kimbers和下面Rodney Hutchers,然后旁边<th>Email<th>和下面abc@gmail.com以及下面def@gmail.com......等我已经搜索了这个论坛或互联网没有找到任何东西谢谢你的时间


心有法竹
浏览 116回答 2
2回答

繁花如伊

只是为了完整起见,当您将 PHP 与 HTML 混合使用时,不需要echo所有内容。&nbsp; &nbsp; //not sure what is above this, so will just end it here.&nbsp; &nbsp; ?>&nbsp; &nbsp; <table>&nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <th>FullName</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>Email</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>City</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>State</th>&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; <?php foreach ($people as $person) : ?>&nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <?php foreach ($person as $key => $values) : ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><?php echo $values; ?></td>&nbsp; &nbsp; &nbsp; &nbsp; <?php endforeach; ?>&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; <?php endforeach; ?>&nbsp; &nbsp; </table>创建完整有效的代码。不要遗漏<tr></tr>,以另一种方式解决 CSS 问题。======另一种做事方式。代码可能看起来有点复杂,但更容易维护。例如,如果您想添加邮政编码,您所要做的就是更改数组$fields。其他一切都会适应。$fields = ['name','email','city','state'];?>&nbsp; &nbsp; <table>&nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <?php foreach($fields as $field): ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <th><?php echo ucfirst($field); ?></th>&nbsp; &nbsp; &nbsp; &nbsp; <?php endforeach; ?>&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp;<?php&nbsp; foreach ($people as $person) : ?>&nbsp;&nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<?php foreach ($fields as $field) :&nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td> <?php echo $person[$field]; ?> </td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<?php endforeach; ?>&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp;<?php endforeach; ?>&nbsp;&nbsp; &nbsp; </table>

12345678_0001

表行需要在第一个循环中。echo "<table>";echo "<th>FullName</th>";echo "<th>Email</th>";echo "<th>City</th>";echo "<th>State</th>";foreach ($people as $person) {&nbsp; &nbsp; echo "<tr>";&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; foreach ($person as $key=>$values) {&nbsp; &nbsp; &nbsp; &nbsp; echo "<td>$values</td>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</tr>";}echo "</table>";
打开App,查看更多内容
随时随地看视频慕课网APP