为了账号安全,请及时绑定邮箱和手机立即绑定

在 PHP 中使用 foreach 语句回显一个 3 维数组

在 PHP 中使用 foreach 语句回显一个 3 维数组

PHP
梵蒂冈之花 2023-04-28 14:16:22
我已经看到了所有与我相关的问题,但仍然没有找到解决我的“简单”问题的方法。我有一个 3 维数组,我只想显示结果。但是当我回应时,. "<td>".$person ['job']."</td>"我收到了错误。任何建议thnx$people= array(array(    "name" => "Jennifer Kimbers",    "age"=>"45",    "email" => "abc@gmail.com",    "city" => "Seattle",    "state" => "Washington"),        array(            "job"=>"web developer"        ),array(    "name" => "Rodney Hutchers",    "age"=>"55",    "email" => "def@gmail.com",    "city" => "Los Angeles",    "state" => "California"),        array(             "job"=>"data developer"         );echo "<table>"    ."<th>FullName</th>"    ."<th>Age</th>"    ."<th>Email</th>"    ."<th>City</th>"    ."<th>State</th>"    ."<th>Job</th>"; foreach ($people as $person) {    echo "<tr>"        . "<td>" . $person ['name'] . "</td>"        . "<td>" . $person ['age'] . "</td>"        . "<td>" . $person ['email'] . "</td>"        . "<td>" . $person ['city'] . "</td>"        . "<td>" . $person ['state'] . "</td>"        . "<td>" . $person ['job'] . "</td>"        . "</tr>";}echo "</table>";
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

您的数组结构略有偏差,在


array(

    "name" => "Jennifer Kimbers",

    "age"=>"45",

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

    "city" => "Seattle",

    "state" => "Washington"),  // Close bracket here

        array(

            "job"=>"web developer"

        ),

这个缩进正确的是


array(

    "name" => "Jennifer Kimbers",

    "age"=>"45",

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

    "city" => "Seattle",

    "state" => "Washington"),

array(

    "job"=>"web developer"),

所以你的循环试图将它用作两个单独的数据位,而第二个不包含你期望的很多字段。


您需要确保在正确的位置关闭数组元素/将作业添加到与其余数据相同的元素中......


array(

    "name" => "Jennifer Kimbers",

    "age"=>"45",

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

    "city" => "Seattle",

    "state" => "Washington",  // Move ) after the job

    "job" => "web developer"

),

如果您需要额外级别的数组,那么您可以将其列为工作列表......


array(

    "name" => "Jennifer Kimbers",

    "age"=>"45",

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

    "city" => "Seattle",

    "state" => "Washington",

    "jobs" => array( "title" => "web developer")

),

显示它们


foreach ($people as $person) {

    echo "<tr>"

        . "<td>" . $person ['name'] . "</td>"

        . "<td>" . $person ['age'] . "</td>"

        . "<td>" . $person ['email'] . "</td>"

        . "<td>" . $person ['city'] . "</td>"

        . "<td>" . $person ['state'] . "</td>"

        . "<td>";

    foreach ( $person['jobs'] as $job ) {

         echo $job . "/";

    }

    echo "</td>"

        . "</tr>";

}

虽然这样你最终会/在职位名称后面有一个尾随,但它显示了原则。您可以代替内部foreach()循环使用...


echo implode("/", $person['jobs']);


查看完整回答
反对 回复 2023-04-28
  • 1 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信