在PHP中用foreach语句回传一个3维数组。

问题描述 投票:3回答:1

我看到了所有与我的问题相关的问题,但仍然没有找到任何解决我的 "简单 "问题的方法,我有一个三维数组,我只是想显示结果。我有一个三维数组,我只是想显示结果。但是,当我要呼应的是 . "<td>".$person ['job']."</td>" I am getting errors. 任何建议thnx

$people= array(

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "[email protected]",
    "city" => "Seattle",
    "state" => "Washington"),
        array(
            "job"=>"web developer"
        ),

array(
    "name" => "Rodney Hutchers",
    "age"=>"55",
    "email" => "[email protected]",
    "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>";
php arrays multidimensional-array
1个回答
5
投票

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

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "[email protected]",
    "city" => "Seattle",
    "state" => "Washington"),  // Close bracket here
        array(
            "job"=>"web developer"
        ),

这个适当的缩进是

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "[email protected]",
    "city" => "Seattle",
    "state" => "Washington"),
array(
    "job"=>"web developer"),

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

你需要确保在正确的地方关闭数组元素,将工作添加到与其他数据相同的元素中... ...

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "[email protected]",
    "city" => "Seattle",
    "state" => "Washington",  // Move ) after the job
    "job" => "web developer"
),

如果你需要额外的数组,那么你可以把它变成一个工作列表... ...

array(
    "name" => "Jennifer Kimbers",
    "age"=>"45",
    "email" => "[email protected]",
    "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']);
© www.soinside.com 2019 - 2024. All rights reserved.