Home Backend Development PHP Tutorial php recursive example

php recursive example

Jul 29, 2016 am 09:14 AM
array dirname return

Recursion as an algorithm is widely used in programming languages. A process or function has a method of directly or indirectly calling itself in its definition or description. It usually transforms a large and complex problem into a smaller problem similar to the original problem to solve. The recursive strategy only A small number of programs are needed to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of program code.

Here are 4 examples of recursion:

<?php
&#160;&#160; &#160;
&#160;&#160; &#160;/*
&#160;&#160; &#160;&#160;&#160; &#160;递归的实例
&#160;&#160; &#160;&#160;&#160; &#160;1、统计数组元素个数
&#160;&#160; &#160;&#160;   php也可以直接使用count($arr,1) 来计算多维数组的元素的个数
&#160;&#160; &#160;&#160;&#160; &#160;2、统计文件和文件夹数量
&#160;&#160; &#160;&#160;&#160; &#160;3、删除文件或文件夹
&#160;&#160; &#160;&#160;&#160; &#160;用到的系统函数:file_exists()检查目录或者文件是否存在 unlink()删除文件 rmdir()删除目录
&#160;&#160; &#160;&#160;&#160; &#160;4、无限极分类的排序
&#160;&#160; &#160;*/

&#160;&#160; &#160;/**
&#160;&#160; &#160;* 递归共计数组元素个数
&#160;&#160; &#160;* @param array $arr 统计的数组
&#160;&#160; &#160;* @return boolean|int&#160; 如果失败返回false,成功返回数组的元素个数
&#160;&#160; &#160;*/
&#160;&#160; &#160;function conarr($arr){
&#160;&#160; &#160;&#160;&#160; &#160;function funtmp($arr,$sum=0){
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;if(is_array($arr)){
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;$sum=count($arr);
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;}else{
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;return count($arr);
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;}
&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &#160;foreach($arr as $k=> $v){
                if(is_array($v)){
                    $sum += funtmp($v,$sum);
                }
            }
            return $sum;
        }
        return funtmp($arr);
    }
    // $arr = array(1,2,3,4,array(1,2,3,array(0,3)));
    // echo conarr($arr).'<br/>';
    // echo count($arr,1);

    /**
    * 递归统计指定目录的子文件的个数和文件夹个数
    * @param $dirname string 目录路径
    * @return array|boolean 返回包含子文件个数和文件夹个数的数组,失败返回false
    */
    function condir($dirname,$data = array('dirnum'=>0,'filenum'=>0)){
        if(!is_dir($dirname)){
            return false;
        }
        $dir = opendir($dirname); //打开句柄
        readdir($dir);//读取点
        readdir($dir);//读取点
        while($filename = readdir($dir)){
            $newfile = $dirname.'/'.$filename;//拼接子文件名
            if(is_dir($newfile)){
                $data['dirnum']++;
                $data['dirnum']+=condir($newfile)['dirnum'];
                $data['filenum']+=condir($newfile)['filenum'];
            }else{
                $data['filenum']++;
            }
        }
        return $data;
    }
    //$a =  condir('C:\wamp\www\test');
    //var_dump($a);

    /**
    * 删除文件或者文件夹
    * @param string $dirname 文件路径
    * @return boolean 删除成功返回true,失败返回false
    */
    function delDir($dirname){
        if(!file_exists($dirname)){return false;}
        if($dir = opendir($dirname)){
            while($filename = readdir($dir)){
                if($filename !="."&& $filename !='..'){
                    $subFile = $dirname.'/'.$filename;
                    if(is_dir($subFile)){
                        delDir($subFile);
                    }
                    if(is_file($subFile)){
                        unlink($subFile);
                    }
                }
            }    
            closedir($dir);
            rmdir($dirname);
        }
        if(!file_exists($dirname)){
            return true;
        }else{
            return false;
        }
    }
    //echo delDir('C:\wamp\www\test');


    //无限极分类排序,父类后跟子类
    function getlist($cate,$pid=0,$html="------",$i=0){
        $i++;
        $list = array();
        foreach($cate as $val){
            if($val['pid']==$pid){
                $val['html']=str_repeat($html,$i-1);
                $list[]=$val;
                $list = array_merge($list,getlist($cate,$val['id'],$html,$i));
            }
        }
        return $list;
    }
?>
Copy after login


The above has introduced PHP recursion examples, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

Simple and clear method to use PHP array_merge_recursive() function Simple and clear method to use PHP array_merge_recursive() function Jun 27, 2023 pm 01:48 PM

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values ​​of the same keys, making the program design more flexible. array_merge

How to use the array_combine function in PHP to combine two arrays into an associative array How to use the array_combine function in PHP to combine two arrays into an associative array Jun 26, 2023 pm 01:41 PM

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values ​​of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

Use the return keyword in JavaScript Use the return keyword in JavaScript Feb 18, 2024 pm 12:45 PM

Usage of return in JavaScript requires specific code examples In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called. The return statement has the following common uses: Return a value The return statement can be used to return a value to the place where the function is called. Here is a simple example: functionadd(a,b){

Detailed explanation of JavaScript function return values ​​and return statements Detailed explanation of JavaScript function return values ​​and return statements Aug 04, 2022 am 09:46 AM

JavaScript functions provide two interfaces to interact with the outside world. The parameters serve as the entrance to receive external information; the return value serves as the outlet to feed back the operation results to the outside world. The following article will take you to understand the JavaScript function return value and briefly analyze the usage of the return statement. I hope it will be helpful to you!

See all articles