PHP正确遍历json_decode返回的stdClass数组,格式化输出API影视数据
现有代码错误原因
- 循环逻辑错位:外层遍历
$animeList拿到的每一项已经是单部电影的stdClass对象,不需要再嵌套一层循环遍历对象的所有属性,否则会把每一个字段(字符串、数组等)都拆成独立的列表项,内容混排。 - 取值语法错误:
stdClass对象的属性需要用->语法访问,不能直接遍历后当普通变量输出。 - 遗漏
people字段处理:没有单独遍历people数组做渲染,这部分内容完全不会显示。 - 无样式间距控制:所有内容没有独立容器分隔,导致条目粘连。
正确实现代码
if ($_GET['fields'] == 'films'): ?> <!-- 电影列表容器,自动给子元素加间距 --> <div style="display: flex; flex-direction: column; gap: 2rem; max-width: 800px; margin: 2rem auto; padding: 0 1rem;"> <?php foreach ($animeList as $film): // 转义所有输出,避免破坏页面结构 $filmTitle = htmlspecialchars($film->title); $filmDesc = htmlspecialchars($film->description); $filmDirector = htmlspecialchars($film->director); $filmProducer = htmlspecialchars($film->producer); $filmReleaseYear = htmlspecialchars($film->release_date); $filmScore = htmlspecialchars($film->rt_score); ?> <!-- 单部电影的卡片容器 --> <div style="border: 1px solid #e5e7eb; border-radius: 8px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1);"> <h2 style="margin-top: 0; margin-bottom: 0.5rem;"><?php echo $filmTitle; ?></h2> <p style="color: #6b7280; font-size: 0.9rem; margin: 0 0 1rem;"> 导演:<?php echo $filmDirector; ?> | 制片:<?php echo $filmProducer; ?> | 上映年份:<?php echo $filmReleaseYear; ?> | 烂番茄评分:<?php echo $filmScore; ?> </p> <p style="line-height: 1.6; color: #374151;"><?php echo $filmDesc; ?></p> <!-- 渲染people字段 --> <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;"> <h4 style="margin: 0 0 0.5rem; font-size: 1rem;">关联人员接口:</h4> <ul style="margin: 0; padding-left: 1.2rem; line-height: 1.6; font-size: 0.9rem;"> <?php foreach ($film->people as $personUrl): $personUrl = htmlspecialchars($personUrl); ?> <li><code style="background: #f3f4f6; padding: 0.1rem 0.3rem; border-radius: 4px;"><?php echo $personUrl; ?></code></li> <?php endforeach; ?> </ul> </div> </div> <?php endforeach; ?> </div> <?php endif; ?>
实现效果说明
- 每部电影独立成卡片,卡片之间自动保留2rem的间距,不会出现内容粘连的问题。
- 正确展示电影的标题、基础元信息、简介内容。
people数组的每一项都会被渲染成独立列表项,以代码样式展示接口地址,不会生成可跳转的外链。- 所有输出都经过
htmlspecialchars转义,避免特殊字符破坏页面结构。
内容的提问来源于stack exchange,提问作者AlecTech
相关产品推荐
相关产品推荐

