php分类实现
PHP分类实现方法
基于数组的分类
使用PHP数组可以快速实现简单的分类功能。通过键值对存储分类信息,便于检索和操作。
$categories = [
'fruit' => ['apple', 'banana', 'orange'],
'vegetable' => ['carrot', 'broccoli', 'spinach']
];
多维数组适合更复杂的分类结构:
$categories = [
[
'id' => 1,
'name' => '电子产品',
'sub' => [
['id' => 11, 'name' => '手机'],
['id' => 12, 'name' => '电脑']
]
]
];
数据库驱动的分类
使用MySQL等关系型数据库存储分类数据是更专业的解决方案。
创建分类表结构:
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
parent_id INT DEFAULT NULL,
FOREIGN KEY (parent_id) REFERENCES categories(id)
);
实现无限级分类查询:
function getCategories($parentId = null) {
$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $db->prepare("SELECT * FROM categories WHERE parent_id " .
($parentId === null ? "IS NULL" : "= :parent_id"));
if ($parentId !== null) {
$stmt->bindParam(':parent_id', $parentId);
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
递归处理分类树
递归算法适合处理多级分类结构。
构建分类树函数:
function buildCategoryTree($parentId = null) {
$categories = getCategories($parentId);
foreach ($categories as &$category) {
$children = buildCategoryTree($category['id']);
if (!empty($children)) {
$category['children'] = $children;
}
}
return $categories;
}
分类数据展示
前端展示分类通常需要转换为HTML结构。
生成嵌套列表:
function renderCategories($categories) {
echo '<ul>';
foreach ($categories as $category) {
echo '<li>' . htmlspecialchars($category['name']);
if (!empty($category['children'])) {
renderCategories($category['children']);
}
echo '</li>';
}
echo '</ul>';
}
分类性能优化
大数据量分类系统需要考虑性能问题。
使用闭包表模式:
CREATE TABLE category_path (
ancestor INT NOT NULL,
descendant INT NOT NULL,
depth INT NOT NULL,
PRIMARY KEY (ancestor, descendant),
FOREIGN KEY (ancestor) REFERENCES categories(id),
FOREIGN KEY (descendant) REFERENCES categories(id)
);
预计算路径查询示例:
function getAllDescendants($categoryId) {
$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $db->prepare("SELECT c.* FROM categories c
JOIN category_path cp ON c.id = cp.descendant
WHERE cp.ancestor = :id AND cp.depth > 0");
$stmt->bindParam(':id', $categoryId);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
分类缓存策略
减少数据库查询次数可显著提升性能。
使用Redis缓存分类数据:
function getCachedCategories() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if (!$redis->exists('categories')) {
$categories = buildCategoryTree();
$redis->set('categories', json_encode($categories));
$redis->expire('categories', 3600); // 1小时过期
return $categories;
}
return json_decode($redis->get('categories'), true);
}






