PHP解析JSON无法正确获取键值按分类输出内容如何解决?
问题原因
- 核心错误出在第二层循环的变量调用:你已经把分类下的所有文章遍历赋值给
$article变量,但输出时误用了存储当前分类所有文章的数组变量$entry去取字段,触发PHP报错,服务端关闭错误显示时就会出现无输出的情况 - 原代码只输出了标题,没有按需求输出文章链接字段,结构也不符合你要的
<p>放链接、<span>放标题的要求
修复后完整代码
<html> <head> </head> <body> <?php $json = '[{ "article": "https://example.com", "category": "Cat2", "title" : "1the title Cat2" }, { "article": "https://example.com", "category": "Cat1", "title" : "1the title Cat1" }, { "article": "https://example.com", "category": "Cat1", "title" : "2the title Cat1" }, { "article": "https://example.com", "category": "Cat2", "title" : "2the title Cat2" }, { "article": "https://example.com", "category": "Cat1", "title" : "3the title Cat1" }]'; $values = json_decode($json, true); $res = []; foreach ($values as $entry) { $category = $entry['category']; if (! array_key_exists($category, $res)) { $res[$category] = []; } $res[$category][] = $entry; } foreach($res as $category => $articles): ?> <h1><?= $category; ?></h1> <?php foreach($articles as $article): ?> <p><?= $article['article']; ?></p> <span><?= $article['title']; ?></span> <?php endforeach; ?> <?php endforeach; ?> </body> </html>
修改点说明
- 把第一层循环的
$entry变量改名为$articles,语义更清晰,避免和原逻辑里的单条数据变量混淆 - 第二层循环输出时改用单条文章变量
$article取对应字段,$article['article']输出文章链接放在<p>标签里,$article['title']输出标题放在<span>标签里,完全匹配你期望的输出结构 - 如果需要调试可以在代码最顶部加
error_reporting(E_ALL);ini_set('display_errors',1);打开错误提示,能快速定位这类变量调用错误
内容的提问来源于stack exchange,提问作者Alex Smith
相关产品推荐
相关产品推荐

