
在web开发中,处理json(javascript object notation)数据是一项常见任务。php提供了强大的内置函数来解析和操作json。本教程将指导您如何将一个包含多条记录的json数组,按照其中一个字段(例如“category”)进行分组,并最终以结构化的html形式展示出来。
首先,我们需要一个JSON字符串作为示例数据。这个JSON字符串包含了一个文章列表,每篇文章都有“article”(链接)、“category”(类别)和“title”(标题)字段。
<?php
$json = '[{
"article": "https://example.com/article1",
"category": "Cat2",
"title" : "1the title Cat2"
}, {
"article": "https://example.com/article2",
"category": "Cat1",
"title" : "1the title Cat1"
}, {
"article": "https://example.com/article3",
"category": "Cat1",
"title" : "2the title Cat1"
}, {
"article": "https://example.com/article4",
"category": "Cat2",
"title" : "2the title Cat2"
}, {
"article": "https://example.com/article5",
"category": "Cat1",
"title" : "3the title Cat1"
}]';
// 使用 json_decode 函数将JSON字符串解码为PHP数组
// 第二个参数 true 表示解码为关联数组,而非对象
$values = json_decode($json, true);
// 检查解码是否成功,以及是否为数组
if (json_last_error() !== JSON_ERROR_NONE || !is_array($values)) {
die("JSON解码失败或数据格式不正确: " . json_last_error_msg());
}
?>json_decode($json, true)是关键一步,它将JSON字符串转换为PHP的关联数组,方便我们通过键名访问数据。
为了按类别显示数据,我们需要对解码后的 $values 数组进行预处理,将其重新组织成一个以类别名为键,值为该类别下所有文章数组的新数组。
<?php
// ... (接上文的 $json 和 $values)
$res = []; // 初始化一个空数组,用于存储按类别分组后的数据
foreach ($values as $entry) {
$category = $entry['category']; // 获取当前文章的类别
// 如果 $res 数组中还没有当前类别作为键,则创建一个空数组
if (! array_key_exists($category, $res)) {
$res[$category] = [];
}
// 将当前文章添加到对应类别的数组中
$res[$category][] = $entry;
}
// 此时,$res 数组的结构将是:
// [
// "Cat2" => [
// ["article" => "...", "category" => "Cat2", "title" => "..."],
// ["article" => "...", "category" => "Cat2", "title" => "..."]
// ],
// "Cat1" => [
// ["article" => "...", "category" => "Cat1", "title" => "..."],
// ["article" => "...", "category" => "Cat1", "title" => "..."],
// ["article" => "...", "category" => "Cat1", "title" => "..."]
// ]
// ]
?>这个 foreach 循环遍历原始文章列表,根据每篇文章的 category 字段,动态地构建了一个新的 $res 数组。array_key_exists() 确保每个类别只初始化一次。
立即学习“PHP免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
数据分组完成后,我们就可以遍历 $res 数组,并将其渲染到HTML页面上。这里使用嵌套的 foreach 循环:外层循环遍历类别,内层循环遍历每个类别下的文章。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文章分类展示</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 20px; }
h1 { color: #333; border-bottom: 2px solid #eee; padding-bottom: 5px; margin-top: 30px; }
p { margin: 5px 0; }
.article-link { color: #007bff; text-decoration: none; }
.article-title { font-weight: bold; color: #555; }
</style>
</head>
<body>
<?php
// ... (接上文的 $json, $values, $res)
foreach($res as $category => $entry_list): // $category 是类别名, $entry_list 是该类别下的文章数组
?>
<h1><?= htmlspecialchars($category); ?></h1>
<?php foreach($entry_list as $article): // $article 是单篇文章的关联数组 ?>
<p>
<a href="<?= htmlspecialchars($article['article']); ?>" class="article-link" target="_blank">
<?= htmlspecialchars($article['article']); ?>
</a>
</p>
<p class="article-title"><?= htmlspecialchars($article['title']); ?></p>
<?php endforeach; ?>
<?php endforeach;
?>
</body>
</html>关键修正点: 在原始问题中,内层循环错误地使用了 <?= $entry['title']; ?>。由于内层循环的变量是 $article,它代表了当前遍历到的单篇文章,因此正确的访问方式应该是 $article['article'] 和 $article['title']。上述代码已进行了修正。
将上述所有部分整合,形成一个完整的PHP脚本:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文章分类展示</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 20px; }
h1 { color: #333; border-bottom: 2px solid #eee; padding-bottom: 5px; margin-top: 30px; }
p { margin: 5px 0; }
.article-link { color: #007bff; text-decoration: none; }
.article-title { font-weight: bold; color: #555; }
</style>
</head>
<body>
<?php
$json = '[{
"article": "https://example.com/article1",
"category": "Cat2",
"title" : "1the title Cat2"
}, {
"article": "https://example.com/article2",
"category": "Cat1",
"title" : "1the title Cat1"
}, {
"article": "https://example.com/article3",
"category": "Cat1",
"title" : "2the title Cat1"
}, {
"article": "https://example.com/article4",
"category": "Cat2",
"title" : "2the title Cat2"
}, {
"article": "https://example.com/article5",
"category": "Cat1",
"title" : "3the title Cat1"
}]';
$values = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($values)) {
die("JSON解码失败或数据格式不正确: " . json_last_error_msg());
}
$res = [];
foreach ($values as $entry) {
$category = $entry['category'];
if (! array_key_exists($category, $res)) {
$res[$category] = [];
}
$res[$category][] = $entry;
}
foreach($res as $category => $entry_list): ?>
<h1><?= htmlspecialchars($category); ?></h1>
<?php foreach($entry_list as $article): ?>
<p>
<a href="<?= htmlspecialchars($article['article']); ?>" class="article-link" target="_blank">
<?= htmlspecialchars($article['article']); ?>
</a>
</p>
<p class="article-title"><?= htmlspecialchars($article['title']); ?></p>
<?php endforeach; ?>
<?php endforeach;
?>
</body>
</html>通过本教程,您应该已经掌握了在PHP中解析JSON数据、根据特定键对数据进行分组,并将分组后的数据渲染到HTML页面的基本方法。理解 json_decode() 的用法、数组操作技巧以及循环遍历时的变量作用域是成功实现此类功能的关键。同时,遵循错误处理和安全实践将有助于构建健壮和可靠的Web应用程序。
以上就是PHP中JSON数据按类别分组与渲染实践指南的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号