John Davidson

php - Echoing out contents under each respective topic using for each loop?

0 comments
Message:


My table is looks like











































Id Topic Sentence
1 Google bla bla..1
2 YouTube bla bla..2
3 Amazon bla bla..3
4 Google bla bla..4
5 Google bla bla..5
6 YouTube bla bla..6


My Answer:
You can achieve this by first organizing the data into an array and then using a foreach loop to echo out the contents under each respective topic. Here's an example code snippet:

php
// Sample data
$table = [
['Id' => 1, 'Topic' => 'Google', 'Sentence' => 'bla bla..1'],
['Id' => 2, 'Topic' => 'YouTube', 'Sentence' => 'bla bla..2'],
['Id' => 3, 'Topic' => 'Amazon', 'Sentence' => 'bla bla..3'],
['Id' => 4, 'Topic' => 'Google', 'Sentence' => 'bla bla..4'],
['Id' => 5, 'Topic' => 'Google', 'Sentence' => 'bla bla..5'],
['Id' => 6, 'Topic' => 'YouTube', 'Sentence' => 'bla bla..6'],
];

// Organize data by topic
$topics = [];
foreach ($table as $row) {
$topics[$row['Topic']][] = $row['Sentence'];
}

// Echo out contents under each respective topic
foreach ($topics as $topic => $sentences) {
echo "

$topic

";
echo "
    ";
    foreach ($sentences as $sentence) {
    echo "
  • $sentence
  • ";
    }
    echo "
";
}


This code snippet will output the contents under each respective topic in an unordered list format. You can customize the HTML structure as needed to fit your requirements.

Rate this post

3 of 5 based on 2173 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us