


Tutorial on grouping and rendering JSON data by category in PHP
Oct 12, 2025 am 09:15 AM1. Understand JSON data structure and PHP decoding
In web development, JSON (JavaScript Object Notation) is a lightweight data exchange format that is widely used for front-end and back-end data transmission. PHP provides built-in functions to process JSON data.
Suppose we have a JSON array containing information about multiple articles. Each article has three fields: "article" (link), "category" (category) and "title" (title). Our goal is to group these articles by "category" and render them on a web page.
Example JSON data:
[ { "article": "https://example.com/cat2-article1", "category": "Cat2", "title": "1the title Cat2" }, { "article": "https://example.com/cat1-article1", "category": "Cat1", "title": "1the title Cat1" }, { "article": "https://example.com/cat1-article2", "category": "Cat1", "title": "2the title Cat1" }, { "article": "https://example.com/cat2-article2", "category": "Cat2", "title": "2the title Cat2" }, { "article": "https://example.com/cat1-article3", "category": "Cat1", "title": "3the title Cat1" } ]
In PHP, we use json_decode() function to convert JSON string into PHP variable. When the second parameter is set to true, it returns an associative array; otherwise, an object is returned. For the needs of this tutorial, associative arrays are easier to work with.
<?php $json = '[{ "article": "https://example.com/cat2-article1", "category": "Cat2", "title" : "1the title Cat2" }, { "article": "https://example.com/cat1-article1", "category": "Cat1", "title" : "1the title Cat1" }, { "article": "https://example.com/cat1-article2", "category": "Cat1", "title" : "2the title Cat1" }, { "article": "https://example.com/cat2-article2", "category": "Cat2", "title" : "2the title Cat2" }, { "article": "https://example.com/cat1-article3", "category": "Cat1", "title" : "3the title Cat1" }]'; // Decode JSON string into PHP associative array $values ??= json_decode($json, true); // Check whether the decoding is successful and the data type if (json_last_error() !== JSON_ERROR_NONE) { echo "JSON decoding error: " . json_last_error_msg(); exit; } if (!is_array($values)) { echo "The decoded data is not an array."; exit; } ?>
2. Group data by categories
The decoded $values ??is an array containing multiple article associative arrays. To display by category, we need to iterate through this array and build a new data structure where each key represents a category and its value is an array containing all articles in that category.
<?php // ... (previous JSON data and decoding code) ... $res = []; // Used to store grouped data foreach ($values ??as $entry) { $category = $entry['category']; // Get the category of the current article // If this category is not yet in the result array, create an empty array to store articles under this category if (! array_key_exists($category, $res)) { $res[$category] = []; } // Add the current article to the array of the corresponding category $res[$category][] = $entry; } // At this time, the structure of the $res array is roughly as follows: //[ // "Cat2" => [ // ["article" => "...", "category" => "Cat2", "title" => "..."], // ["article" => "...", "category" => "Cat2", "title" => "..."] // ], // "Cat1" => [ // ["article" => "...", "category" => "Cat1", "title" => "..."], // ["article" => "...", "category" => "Cat1", "title" => "..."], // ["article" => "...", "category" => "Cat1", "title" => "..."] // ] // ] ?>
3. Render grouped data to HTML
Once the data is grouped, the next step is to render it onto an HTML page. This usually involves nested foreach loops: the outer loop iterates over the categories, and the inner loop iterates over the articles under each category.
When rendering, you need to pay attention to correctly accessing the article (link) and title (title) fields of each article. Possible errors in the original question were trying to access variables of the outer loop within the inner loop, or using the wrong key name.
<title>Article classification display</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h1 { color: #333; border-bottom: 2px solid #eee; padding-bottom: 5px; margin-top: 30px; } p { margin: 5px 0; } p.article-link { color: #007bff; } p.article-title { font-weight: bold; } </style> <?php // ... (previous JSON data, decoding and grouping code) ... // Traverse the grouped data and render to HTML foreach($res as $category => $entry_list): ?> <h1>= htmlspecialchars($category); ?></h1> <?php foreach($entry_list as $article): ?> <p class="article-link"><a href="<?=%20htmlspecialchars(%24article%5B'article'%5D);%20?>" target="_blank">= htmlspecialchars($article['article']); ?></a></p> <p class="article-title">= htmlspecialchars($article['title']); ?></p> <?php endforeach; ?> <?php endforeach; ?>
Code explanation and notes:
- htmlspecialchars(): It is crucial to use the htmlspecialchars() function when outputting any data that may come from external or user sources to HTML, to prevent cross-site scripting attacks (XSS).
- Variable naming: In the inner loop, $entry_list is an array of all articles under the current category, and $article is an array of individual articles in $entry_list. Therefore, when accessing article links and titles, $article['article'] and $article['title'] should be used. This is a common error point in the original question, i.e. misuse of variables or wrong keys in the outer loop.
- HTML structure: The sample code uses
tags to display category names, tags, and
tags to display article links and titles to provide a clear structure.
4. Complete sample code
Here is the complete PHP file that integrates all the steps and can be run directly to see the effect:
<title>Article classification display</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h1 { color: #333; border-bottom: 2px solid #eee; padding-bottom: 5px; margin-top: 30px; } p { margin: 5px 0; } p.article-link { color: #007bff; } p.article-title { font-weight: bold; } </style> <?php $json = '[{ "article": "https://example.com/cat2-article1", "category": "Cat2", "title" : "1the title Cat2" }, { "article": "https://example.com/cat1-article1", "category": "Cat1", "title" : "1the title Cat1" }, { "article": "https://example.com/cat1-article2", "category": "Cat1", "title" : "2the title Cat1" }, { "article": "https://example.com/cat2-article2", "category": "Cat2", "title" : "2the title Cat2" }, { "article": "https://example.com/cat1-article3", "category": "Cat1", "title" : "3the title Cat1" }]'; // 1. Decode JSON data $values ??= json_decode($json, true); // Error handling if (json_last_error() !== JSON_ERROR_NONE) { echo "<p style='color:red;'>JSON decoding error: " . json_last_error_msg() . ""; exit; } if (!is_array($values)) { echo "<p style="'color:red;'">The decoded data is not an array.</p>"; exit; } // 2. Group data by category $res = []; foreach ($values ??as $entry) { $category = $entry['category']; if (! array_key_exists($category, $res)) { $res[$category] = []; } $res[$category][] = $entry; } // 3. Render the grouped data to HTML foreach($res as $category => $entry_list): ?> <h1>= htmlspecialchars($category); ?></h1> <?php foreach($entry_list as $article): ?> <p class="article-link"><a href="<?=%20htmlspecialchars(%24article%5B'article'%5D);%20?>" target="_blank">= htmlspecialchars($article['article']); ?></a></p> <p class="article-title">= htmlspecialchars($article['title']); ?></p> <?php endforeach; ?> <?php endforeach; ?>
Summarize
This tutorial demonstrates the complete process of processing JSON data in PHP: from using the json_decode function to convert a JSON string into an operable PHP array, to grouping data by specific keys (such as "category") through traversal and conditional judgment, and finally rendering the grouped data to an HTML page in a clear and safe manner through nested loops. Understanding this data processing pattern is critical to building dynamic web applications, helping developers organize and present complex data sets effectively. In actual development, it is important to pay attention to the security of error handling and output content to improve the robustness of the application and its ability to resist potential attacks.
The above is the detailed content of Tutorial on grouping and rendering JSON data by category in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

Use the ZipArchive class to create a ZIP file. First instantiate and open the target zip, add files with addFile, support custom internal paths, recursive functions can package the entire directory, and finally call close to save to ensure that PHP has write permissions.
