How can data from a table with common elements be displayed in PHP?
When displaying data from a table with common elements in PHP, you can use a loop to iterate through the results and group them based on the common elements. One approach is to store the common elements in an array and use them as keys to group the data accordingly.
// Sample data from a table with common elements
$data = [
['category' => 'fruit', 'name' => 'apple'],
['category' => 'fruit', 'name' => 'banana'],
['category' => 'vegetable', 'name' => 'carrot'],
['category' => 'fruit', 'name' => 'orange'],
['category' => 'vegetable', 'name' => 'lettuce'],
];
// Group data by 'category'
$groupedData = [];
foreach ($data as $row) {
$category = $row['category'];
if (!isset($groupedData[$category])) {
$groupedData[$category] = [];
}
$groupedData[$category][] = $row['name'];
}
// Display the grouped data
foreach ($groupedData as $category => $items) {
echo $category . ': ' . implode(', ', $items) . '<br>';
}