| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Storage;
- class CategoryController extends Controller
- {
- protected static int $nextId = 1;
- public function index()
- {
- $categories = $this->loadCategories();
- $books = $this->loadBooks();
- // 获取一级分类和对应的书籍
- $categoryData = [];
- foreach ($categories as $category) {
- if ($category['level'] == 1) {
- $categoryBooks = array_filter($books, function ($book) use ($category) {
- return $book['category_id'] == $category['id'];
- });
- $categoryData[] = [
- 'category' => $category,
- 'books' => array_slice(array_values($categoryBooks), 0, 3)
- ];
- }
- }
- return view('library.index', compact('categoryData', 'categories'));
- }
- public function show($id)
- {
- $categories = $this->loadCategories();
- $books = $this->loadBooks();
- $currentCategory = collect($categories)->firstWhere('id', $id);
- if (!$currentCategory) {
- abort(404);
- }
- // 获取子分类
- $subCategories = array_filter($categories, function ($cat) use ($id) {
- return $cat['parent_id'] == $id;
- });
- // 获取该分类下的书籍
- $categoryBooks = array_filter($books, function ($book) use ($id) {
- return $book['category_id'] == $id;
- });
- // 获取面包屑
- $breadcrumbs = $this->getBreadcrumbs($currentCategory, $categories);
- return view('library.category', compact('currentCategory', 'subCategories', 'categoryBooks', 'breadcrumbs'));
- }
- private function loadCategories()
- {
- //$json = Storage::disk('public')->get('data/categories.json');
- $json = file_get_contents(public_path("app/palicanon/category/default.json"));
- $tree = json_decode($json, true);
- $flat = self::flattenWithIds($tree);
- return $flat;
- }
- private function loadBooks()
- {
- $json = Storage::disk('public')->get('data/books.json');
- return json_decode($json, true);
- }
- public static function flattenWithIds(array $tree, int $parentId = 0, int $level = 1): array
- {
- $flat = [];
- foreach ($tree as $node) {
- $currentId = self::$nextId++;
- $item = [
- 'id' => $currentId,
- 'parent_id' => $parentId,
- 'name' => $node['name'] ?? null,
- 'tag' => $node['tag'] ?? [],
- "description" => "佛教戒律经典",
- 'level' => $level,
- ];
- $flat[] = $item;
- if (isset($node['children']) && is_array($node['children'])) {
- $childrenLevel = $level + 1;
- $flat = array_merge($flat, self::flattenWithIds($node['children'], $currentId, $childrenLevel));
- }
- }
- return $flat;
- }
- private function getBreadcrumbs($category, $categories)
- {
- $breadcrumbs = [];
- $current = $category;
- while ($current) {
- array_unshift($breadcrumbs, $current);
- $current = collect($categories)->firstWhere('id', $current['parent_id']);
- }
- return $breadcrumbs;
- }
- }
|