review

Last time, we talked about the basics of real-world PHP data structure recursion. So just to review what is recursion?

In general, recursion is called a call to the function itself.

The practical use of recursion in development

N level classification

Infinite level classification is a common requirement in normal development and is encountered in many interview questions. No matter what project you work on, you’ve probably encountered similar problems. Now, let’s use the idea of recursion and put it to the test.

  • SQL structure
CREATE TABLE `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `categoryName` varchar(100) NOT NULL.`parentCategory` int(11) DEFAULT '0'.`sortInd` int(11) NOT NULL,
  PRIMARY KEY (`id`))ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
Copy the code

And then we’re going to virtualize some data, and we’re going to end up looking like this.

Let’s look directly at the code implementation.


      
$dsn = "Mysql: host = 127.0.0.1; port=3306; dbname=light-tips; charset=UTF8;";
$username = 'root';
$password = 'admin';
$pdo = new PDO($dsn, $username, $password);
$sql = 'SELECT * FROM `categories` ORDER BY `parentCategory`, `sortInd`';
$result = $pdo->query($sql, PDO::FETCH_OBJ);
$categories = [];
foreach ($result as $category) {
    $categories[$category->parentCategory][] = $category;
}
function showCategoryTree($categories, $n)
{
    if (isset($categories[$n])) {
        foreach ($categories[$n] as $category) {
            echo str_repeat(The '-', $n) . $category->categoryName . PHP_EOL; showCategoryTree($categories, $category->id); }}return;
}
showCategoryTree($categories, 0);
Copy the code

As you can see, we first get all the data, and then we sort it by parent ID. This is a very nice data structure. Imagine breaking down the problem of showing all the subdirectories in a top-level directory into showing your own class target and showing the subdirectories in the data where parentCategory is the id of the current directory, and then using the start recursive call. The final output looks like this.

Infinitely nested comments

Let’s take a look at what this infinitely nested comment looks like. As shown in figure:

The chestnut above is another classic case that can be solved recursively. Again, let’s look at the data structure.

CREATE TABLE `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `comment` varchar(500) NOT NULL.`username` varchar(50) NOT NULL.`datetime` datetime NOT NULL.`parentID` int(11) NOT NULL.`postID` int(11) NOT NULL,
  PRIMARY KEY (`id`))ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
Copy the code

You can try it out on your own. Don’t read the following.


      
$dsn = "Mysql: host = 127.0.0.1; port=3306; dbname=light-tips; charset=UTF8;";
$username = 'root';
$password = 'admin';
$pdo = new PDO($dsn, $username, $password);
$sql = 'SELECT * FROM `comments` WHERE `postID` = :id ORDER BY `parentId`, `datetime`';
$stmt = $pdo->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute([':id'= >1]);
$result = $stmt->fetchAll();
$comments = [];
foreach ($result as $comment) {
    $comments[$comment->parentID][] = $comment;
}
function showComments(array $comments, $n)
{
    if (isset($comments[$n])) {
        foreach ($comments[$n] as $comment) {
            echo str_repeat(The '-', $n) . $comment->comment . PHP_EOL; showComments($comments, $comment->id); }}return;
}
showComments($comments, 0);
Copy the code

Document scanning

Use recursion to scan directory files.


      
function showFiles(string $dir, array &$allFiles)
{
    $files = scandir($dir);
    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if(! is_dir($path)) { $allFiles[] = $path; }else if($value ! ="."&& $value ! ="..") { showFiles($path, $allFiles); $allFiles[] = $path; }}return;
}
$files = [];
showFiles('. ', $files);
foreach ($files as $file) {
    echo $file . PHP_EOL;
}
Copy the code

More content

PHP basic data structures topic series directory address: github.com/… PHP syntax is used to summarize basic data structures and algorithms. There are also some basic knowledge that is easily overlooked in our daily PHP development and some practical suggestions on specification, deployment and optimization in modern PHP development, as well as in-depth research on the characteristics of the Javascript language.