Home > Article > Backend Development > [Summary sharing] Efficient PHP loop query subcategory method
In the field of Web development, classification query is a very common requirement. Whether it is an e-commerce platform or a content management system, there is a data display method based on classification. As the number of classification layers increases, the task of querying sub-categories becomes more and more complex. This article will introduce an efficient PHP loop query method for subcategories to help developers easily manage category hierarchies.
First, we need to get classified data. Here we take a simple database table as an example. Assume that this table is named category and has the following fields:
id | name | parent_id |
---|---|---|
1 | household appliances | 0 |
手机digital | 0 | |
TV | 1 | |
refrigerator | 1 | |
手机 | 2 | |
Laptop | 2 |
function get_children_categories($parent_id) { // <code to query categories from database by parent_id> return $categories; }In the above code, we will query all subcategories from the database and return them for our further use.
function get_children_categories($parent_id) { $categories = array(); // <code to query categories from database by parent_id> foreach($results as $result) { $category = array(); $category['id'] = $result['id']; $category['name'] = $result['name']; $children = get_children_categories($result['id']); if (!empty($children)) { $category['children'] = $children; } $categories[] = $category; } return $categories; }The above code recursively queries the subcategories of each category layer by layer and adds them to the result set, thereby building a complete classification hierarchy. In this process, we will use PHP's foreach loop and recursively call our own methods.
function print_categories($categories) { echo "<ul>"; foreach($categories as $category) { echo "<li>" . $category['name'] . "</li>"; if (!empty($category['children'])) { print_categories($category['children']); } } echo "</ul>"; }Here, we will traverse each category and output their names. If the category contains subcategories, call your own method recursively and print out all subcategories.
$memcached = new Memcached(); $memcached->addServer('localhost', 11211); $categories = $memcached->get('categories:1'); if (!$categories) { $categories = get_children_categories(1); $memcached->set('categories:1', $categories); } print_categories($categories);In the above code, we first established a memcached client connection and cached the classification results into the cache key named "categories:1". In subsequent queries, we can get the results directly from the cache without re-executing the query function. This approach can significantly improve query performance, especially for large-scale categorical data.
The above is the detailed content of [Summary sharing] Efficient PHP loop query subcategory method. For more information, please follow other related articles on the PHP Chinese website!