如何用PHP/JSON数组构建Bootstrap表格?
问题描述
我需要把如下JSON数据(示例:{"endpoint":"127.0.0.1","id":1,"identifiers":["license:LICENSEKEY","xbl:XBLKEY","live:LIVEKEY","discord:DISCORDID","fivem:FIVEMKEY","license2:LICENSE2KEY"],"name":"Username","ping":54})展示为Bootstrap样式表格。目前已完成表格基础搭建,但无法从identifiers数组中正确提取并显示Rockstar License、Discord ID、Steam Identifier到对应列,需解决数组循环提取值的问题。
当前使用的表格代码:
<table class="table table-striped"> <thead> <tr> <th> ID</th> <th> Player Name</th> <th> License (Rockstar License)</th> <th> Discord ID</th> <th> Steam Identifier</th> <th> Ping</th> </tr> </thead> <tbody> <tr> <?php foreach ($json as $player){ ?> <td> <?php echo $player['id']; ?> </td> <td><?php echo $player['name']; ?> </td> <td><?php echo $player['license']; ?> </td> <td><?php echo $player['discord']; ?> </td> <td><?php echo $player['steam']; ?> </td> <td> <span class="badge badge-pill badge-danger"><?php echo $player['ping']; ?> </span></td> </td> </tr> <?php } ?> </tbody> </table>
解决方案
核心问题是原代码直接尝试访问$player['license']这类字段,但这些数据实际嵌套在identifiers数组中,每个元素为类型:值的格式。需先遍历identifiers数组,拆分出对应类型的值,再填充到表格中。
改造后的完整代码:
<table class="table table-striped"> <thead> <tr> <th>ID</th> <th>玩家名称</th> <th>Rockstar License</th> <th>Discord ID</th> <th>Steam Identifier</th> <th>Ping</th> </tr> </thead> <tbody> <?php foreach ($json as $player) { // 初始化需要的标识符变量,避免无对应值时报错 $license = ''; $discord = ''; $steam = ''; // 遍历identifiers数组,拆分类型与对应值 foreach ($player['identifiers'] as $identifier) { // 按冒号拆分,限制拆分次数为2,防止值中含冒号导致错误 $parts = explode(':', $identifier, 2); $type = $parts[0]; $value = $parts[1] ?? ''; // 匹配目标标识符类型,赋值给对应变量 switch ($type) { case 'license': $license = $value; break; case 'discord': $discord = $value; break; case 'steam': $steam = $value; break; // 如需支持其他标识符类型,可在此扩展case } } ?> <tr> <td><?php echo $player['id']; ?></td> <td><?php echo $player['name']; ?></td> <td><?php echo $license; ?></td> <td><?php echo $discord; ?></td> <td><?php echo $steam; ?></td> <td><span class="badge badge-pill badge-danger"><?php echo $player['ping']; ?></span></td> </tr> <?php } ?> </tbody> </table>
关键说明
- 使用
explode(':', $identifier, 2)拆分标识符,避免值中包含冒号导致的拆分错误。 - 提前初始化变量,确保即使玩家未绑定某类标识符(如无Steam账号),表格列也能正常显示空值而非报错。
- 通过
switch语句精准匹配目标标识符类型,提取对应值填充到表格列中。
内容的提问来源于stack exchange,提问作者Mindless Chaos
相关产品推荐
相关产品推荐

