亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. Understand JSON data structure and PHP decoding
2. Group data by categories
3. Render grouped data to HTML
4. Complete sample code
Summarize
Home Backend Development PHP Tutorial Tutorial on grouping and rendering JSON data by category in PHP

Tutorial on grouping and rendering JSON data by category in PHP

Oct 12, 2025 am 09:15 AM

Tutorial on grouping and rendering JSON data by category in PHP

This tutorial details how to handle complex data in JSON format in PHP. Convert the JSON string into a PHP array through json_decode, then demonstrate how to efficiently group the data according to a specific key (such as "category"), and finally display the grouped data in a structured HTML form through a nested loop to ensure that the article links and titles under each category can be presented correctly.

1. 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 = &#39;[{
    "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"
}]&#39;;

// 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[&#39;category&#39;]; // 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 = &#39;[{
    "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"
}]&#39;;

// 1. Decode JSON data $values ??= json_decode($json, true);

// Error handling if (json_last_error() !== JSON_ERROR_NONE) {
    echo "<p style=&#39;color:red;&#39;>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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

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

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

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

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

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

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

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

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

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

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

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

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

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

How to create a zip archive of files in PHP? How to create a zip archive of files in PHP? Sep 18, 2025 am 12:42 AM

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.

See all articles