Home  >  Article  >  Backend Development  >  PHP uses recursive algorithm to traverse an array infinitely sample code

PHP uses recursive algorithm to traverse an array infinitely sample code

怪我咯
怪我咯Original
2017-07-12 11:41:391952browse

RecursiveThe algorithm transforms the problem into a sub-problem of the same type that has been reduced in size. A function (or procedure) is then called recursively to represent the solution to the problem.

A process (or function) calls itself directly or indirectly. This process (or function) is called a recursive process (or function).

This article mainly introduces the use of PHPRecursionInfinite AlgorithmTraverse Array, combined with the example form to analyze PHP's general traversal for one-dimensional array, two-dimensional array and multi-dimensional irregular array Tips, friends in need can refer to as follows:

<?php
//无限遍历数组
$a1 = array("a", "b", "c"); //一维数组
$a2 = array(array(21, 3, 6), array("a", "b", "c")); //二维数组
$a3 = array(array(array(5, 55), 4, 444), 2, 7, 6, 8, array("w", "d", array(3, 2, "a"), "s")); //多维不规则数组
function fun($a) {
  foreach ($a as $val) {
    if (is_array($val)) { //如果键值是数组,则进行函数递归调用
      fun($val);
    } else { // 如果键值是数值,则进行输出
      echo "$val<br />";
    } //end if
    
  } //end foreach
  
} //end fun
//fun($a1);
//fun($a2);
fun($a3);
?>

Output:

5
55
4
444
2
7
6
8
w
d
3
2
a
s

The above is the detailed content of PHP uses recursive algorithm to traverse an array infinitely sample code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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