You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用while循环、指针与current()函数显示PHP多维关联数组

问题解决:用数组指针+while循环展示多维关联数组

你的代码里有两个核心问题需要修正,同时完善输出逻辑:

1. 变量名不一致问题

你定义的数组变量是$users,但后续指针操作(reset($utilisateurs)、current($utilisateurs))用了法语变量名$utilisateurs,这会导致PHP找不到变量直接报错。

2. 完善输出逻辑

current($users)会返回当前指针位置的子数组(比如第一个是["name"=>"Edouard", ...]),你需要从这个子数组里取出对应键的值。

修正后的完整代码

<style type="text/css">
*
{
    margin: unset;
    box-sizing: border-box;
    font-family: arial;
}

table
{
    margin: 0px 0px 0px 10px;
    border-collapse: collapse;
}

.col
{
    border: 1px solid black;
    padding: 5px 10px 5px 10px;
    font-size: 10pt;
}

th
{
    font-size: 12pt !important;
    color: white;
    background-color: orange;
    text-align: center;
}
</style>
<?php
    // Variables declaration
    $users = array(
        "pseudo1" => array("name"=>"Edouard", "firstname"=>"Louis", "email"=>"louis@gmail.com", "passwd"=>hash("md5", "Road66")),
        "pseudo2" => array("name"=>"Edouard", "firstname"=>"Louis", "email"=>"louis@gmail.com", "passwd"=>hash("md5", "Road66")),
        "pseudo3" => array("name"=>"Edouard", "firstname"=>"Louis", "email"=>"louis@gmail.com", "passwd"=>hash("md5", "Road66")),
        "pseudo4" => array("name"=>"Edouard", "firstname"=>"Louis", "email"=>"louis@gmail.com", "passwd"=>hash("md5", "Road66"))
    );

    // To verify that created array contains the right elements
    var_dump($users);
?>
<br>
<br>
<table>
    <tr>
        <th class="col">Name</th>
        <th class="col">Firstname</th>
        <th class="col">Email address</th>
        <th class="col">Password</th>
    </tr>
<?php
// Reset of pointer - 修正变量名
reset($users);

// 优化循环条件:避免数组元素为false时提前终止
while (($currentUser = current($users)) !== false)
{
?>
    <tr>
        <td class="col"><?php echo $currentUser["name"]; ?></td>
        <td class="col"><?php echo $currentUser["firstname"]; ?></td>
        <td class="col"><?php echo $currentUser["email"]; ?></td>
        <td class="col"><?php echo $currentUser["passwd"]; ?></td>
    </tr>
<?php
    next($users);
}
?>
</table>

关键说明

  • reset($users):将数组指针重置到第一个元素,确保循环从开头开始。
  • ($currentUser = current($users)) !== false:先把当前指针位置的子数组赋值给$currentUser,再判断是否为false(指针走到数组末尾时current()会返回false),这样比单纯用current($users)更安全,避免数组元素本身是false/空值导致循环提前结束。
  • $currentUser["name"]:从当前子数组中取出对应键的值,完成表格内容填充。
  • next($users):每次循环后移动数组指针到下一个元素,直到指针走到数组末尾,循环终止。

内容的提问来源于stack exchange,提问作者louis342398372

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:10:31