How to group news by category in php from mysql
To group news by category in PHP from MySQL, you can use the following steps:
Step 1: Connect to the MySQL database
Use the mysqli
or PDO
extension to connect to your MySQL database. For example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "news_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
?>
Step 2: Retrieve the news data from the database
Use a SQL query to retrieve the news data from the database. For example:
<?php
$sql = "SELECT * FROM news";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$news[] = $row;
}
} else {
echo "0 results";
}
?>
Step 3: Group the news by category
Use a PHP array to group the news by category. You can use the array_group_by
function from the array
extension or create your own function to group the news.
For example, using the array_group_by
function:
<?php
$categories = array_group_by($news, 'category');
foreach ($categories as $category => $news) {
echo "<h2>$category</h2>";
foreach ($news as $news_item) {
echo "<p>". $news_item['title']. "</p>";
}
}
?>
Or, creating your own function:
<?php
function group_by_category($news) {
$categories = array();
foreach ($news as $news_item) {
$category = $news_item['category'];
if (!isset($categories[$category])) {
$categories[$category] = array();
}
$categories[$category][] = $news_item;
}
return $categories;
}
$categories = group_by_category($news);
foreach ($categories as $category => $news) {
echo "<h2>$category</h2>";
foreach ($news as $news_item) {
echo "<p>". $news_item['title']. "</p>";
}
}
?>
Step 4: Display the grouped news
Use a loop to display the grouped news. For example:
<?php
foreach ($categories as $category => $news) {
echo "<h2>$category</h2>";
foreach ($news as $news_item) {
echo "<p>". $news_item['title']. "</p>";
}
}
?>
This will display the news grouped by category, with each category heading followed by the corresponding news items.
Note: Make sure to replace the news
table and category
column with your actual table and column names.