How can one efficiently retrieve categories and their corresponding items from a database table in PHP?
To efficiently retrieve categories and their corresponding items from a database table in PHP, you can use a SQL query to fetch the data and then organize it into a nested array structure where each category contains its corresponding items. This can be achieved by looping through the query results and building the nested array dynamically.
// Assume $db is the database connection object
// Query to retrieve categories and items
$query = "SELECT category, item FROM your_table ORDER BY category";
$result = $db->query($query);
// Initialize an empty array to store categories and items
$categories = [];
// Loop through the query results and organize data into nested array
while ($row = $result->fetch_assoc()) {
$category = $row['category'];
$item = $row['item'];
// Check if category already exists in the array
if (!isset($categories[$category])) {
$categories[$category] = [];
}
// Add item to the corresponding category
$categories[$category][] = $item;
}
// Output the nested array structure
print_r($categories);
Keywords
Related Questions
- What are some best practices for handling file type detection in PHP when downloading files using curl?
- How can PHP classes be utilized to improve the functionality of a block system for website design?
- How can PHP be used to dynamically generate URLs with additional parameters, such as style changes, for website navigation?