递归解决无限级分类的问题
小弟手中有分类3406条,存在category表中。现在用递归解决分类,做成select,如下图:
下面是PHP代码,但是生成select后有错误:
<code>// $result是从数据库中读出的二维数组 $result = array(); while (($row = $info->fetch_array(MYSQLI_ASSOC)) != false) { // 改变数组的索引为分类的id $result[$row['id']] = $row; } $str = ''; $str .= "<select id="category">"; foreach ($result as $value) { if ($value['parent_id'] == 0) { $str .= "<option id="{$value[">{$value['title']}</option>"; $str .= get_children($value['id'], $result, 1); } } $str .= "</select>"; function get_children($id, &$result, $index) { $str = ''; foreach ($result as $key => $value) { if ($id == $value['parent_id']) { $str .= "<option id="{$value[">".str_repeat('---', $index)."{$value['title']}</option>"; $str .= get_children($value['id'], $result, $index + 1); unset($result[$value['id']]); // 存在并且去掉这个以为数组 //echo count($result).'<br>'; } } return $str; } // 打印出select echo $str; </code>
上面代码中,去掉unset执行最后的结果是对的,但是执行时间一般在八九秒。我的想法是存在这一条后把这一条从result结果集中去掉,这样的话以后循环的时候减少循环的次数,然后就能减少执行的时间,但是执行的结果是不对的,只存在省下面的一个地市,其余的地市没有了,研究了半天,也没有发现哪里错,请大神指正。
PS: 1。第一次发帖,不怎么会用,请谅解小弟。
2。有没有更好的办法递归3400多个分类。。
3.谢谢。。
回复内容:
小弟手中有分类3406条,存在category表中。现在用递归解决分类,做成select,如下图:
下面是PHP代码,但是生成select后有错误:
<code>// $result是从数据库中读出的二维数组 $result = array(); while (($row = $info->fetch_array(MYSQLI_ASSOC)) != false) { // 改变数组的索引为分类的id $result[$row['id']] = $row; } $str = ''; $str .= "<select id="category">"; foreach ($result as $value) { if ($value['parent_id'] == 0) { $str .= "<option id="{$value[">{$value['title']}</option>"; $str .= get_children($value['id'], $result, 1); } } $str .= "</select>"; function get_children($id, &$result, $index) { $str = ''; foreach ($result as $key => $value) { if ($id == $value['parent_id']) { $str .= "<option id="{$value[">".str_repeat('---', $index)."{$value['title']}</option>"; $str .= get_children($value['id'], $result, $index + 1); unset($result[$value['id']]); // 存在并且去掉这个以为数组 //echo count($result).'<br>'; } } return $str; } // 打印出select echo $str; </code>
上面代码中,去掉unset执行最后的结果是对的,但是执行时间一般在八九秒。我的想法是存在这一条后把这一条从result结果集中去掉,这样的话以后循环的时候减少循环的次数,然后就能减少执行的时间,但是执行的结果是不对的,只存在省下面的一个地市,其余的地市没有了,研究了半天,也没有发现哪里错,请大神指正。
PS: 1。第一次发帖,不怎么会用,请谅解小弟。
2。有没有更好的办法递归3400多个分类。。
3.谢谢。。
关系数据库中的无限深度树状关系的表示有两种常见方案:
- edge list tree(又写作adjacency list,即邻接表)
一行的表示类似于(子元素id, 父元素id)
- nested set tree(即左右值)
一行的表示类似于(当前元素左值, 当前元素右值)
相信楼主用的是前者,这样的坏处是需要递归查询。而后者更易于查询,一条sql即可搞定,见@沙渺 的这篇文章。
针对lz的问题,如果嵌套关系表示使用的是左右值方法,拿到全量数据的前提下,在PHP中也可以用O(n)方式迭代数据得到所有需要的子节点和深度等数据,非常简单。
如果只是需要在前端使用这些树状数据,那么公子的方案是最简单的,比用数据库邻接表、服务器端递归遍历简单多了。
关于nested set:
- WIKI: Nested Set Model
- Nested Set的主要使用流程(常用查询,增删节点的方式等)
- nested set与adjacency list效率比较,以及如何使用R-tree索引进行进一步提速
- 一个把edge list转化为nested set的mysql存储过程
这种东西干嘛要存到数据库中啊 =_=! http://www.soulteary.com/2013/05/10/jquery-city-select.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
