通俗地说就是使用 PHP 的递归函数

发布于 2024-08-29 05:48:06 字数 105 浏览 4 评论 0原文

谁能用外行语言并使用示例向我解释 PHP 中的递归函数(不使用斐波那契)?我正在看一个例子,但斐波那契完全迷失了我!

先感谢您 ;-) 另外,您在 Web 开发中多久使用它们一次?

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci totally lost me!

Thank you in advance ;-)
Also how often do you use them in web development?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

情绪 2024-09-05 05:48:06

外行术语:

递归函数是一个调用自身的函数。

更深入一点:

如果函数不断调用自身,它如何知道何时停止?您设置一个条件,称为基本情况。基本情况告诉我们的递归调用何时停止,否则它将无限循环。

因为我有很强的数学背景,所以对我来说一个很好的学习例子是阶乘。从下面的评论来看,阶乘函数似乎有点太多了,我将其留在这里以防万一您需要它。

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

关于在 Web 开发中使用递归函数,我个人并不使用递归调用。并不是说我认为依赖递归是不好的做法,但它们不应该是您的首选。如果使用不当,它们可能会致命。

虽然我无法与目录示例竞争,但我希望这会有所帮助。

(4/20/10) 更新:

检查这个问题也很有帮助,其中接受的答案以外行术语演示了递归函数如何工作。尽管OP的问题涉及Java,但概念是相同的,

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n) {
  if ($n === 0) { // our base case
     return 1;
  }
  else {
     return $n * fact($n-1); // <--calling itself.
  }
}

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

Although I cannot compete with the directory example, I hope this helps somewhat.

(4/20/10) Update:

It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,

携君以终年 2024-09-05 05:48:06

一个例子是打印给定目录的任何子目录中的每个文件(如果这些目录中没有符号链接,这可能会以某种方式破坏函数)。打印所有文件的伪代码如下所示:

function printAllFiles($dir) {
    foreach (getAllDirectories($dir) as $f) {
        printAllFiles($f); // here is the recursive call
    }
    foreach (getAllFiles($dir) as $f) {
        echo $f;
    }
}

想法是先打印所有子目录,然后打印当前目录的文件。这个想法适用于所有子目录,这就是为所有子目录递归调用此函数的原因。

如果你想尝试这个例子,你必须检查特殊目录 ...,否则你会陷入调用 printAllFiles(".")< /code> 一直。此外,您必须检查要打印的内容以及当前的工作目录是什么(请参阅opendir()getcwd()...)。

An example would be to print every file in any subdirectories of a given directory (if you have no symlinks inside these directories which may break the function somehow). A pseudo-code of printing all files looks like this:

function printAllFiles($dir) {
    foreach (getAllDirectories($dir) as $f) {
        printAllFiles($f); // here is the recursive call
    }
    foreach (getAllFiles($dir) as $f) {
        echo $f;
    }
}

The idea is to print all sub directories first and then the files of the current directory. This idea get applied to all sub directories, and thats the reason for calling this function recursively for all sub directories.

If you want to try this example you have to check for the special directories . and .., otherwise you get stuck in calling printAllFiles(".") all the time. Additionally you must check what to print and what your current working directory is (see opendir(), getcwd(), ...).

撩动你心 2024-09-05 05:48:06

递归是一种不断重复的东西。就像一个从自身内部调用自身的函数。让我用一个有点伪的例子来演示:

想象一下,你和你的朋友出去喝啤酒,但如果你在午夜之前不回家,你的妻子就会让你生气。为此,我们创建 orderAndDrinkBeer($time) 函数,其中 $time 是午夜减去您喝完当前饮料并回家所需的时间。

因此,到达酒吧后,您点了第一杯啤酒并开始喝酒:

$timeToGoHome = '23';  // Let's give ourselves an hour for last call and getting home

function orderAndDrinkBeer($timeToGoHome) {  // Let's create the function that's going to call itself.
    $beer = New Beer();  // Let's grab ourselves a new beer
    $currentTime = date('G'); // Current hour in 24-hour format

    while ($beer->status != 'empty') {  // Time to commence the drinking loop
        $beer->drink();  // Take a sip or two of the beer(or chug if that's your preference)
    }

    // Now we're out of the drinking loop and ready for a new beer

    if ($currentTime < $timeToGoHome) { // BUT only if we got the time
        orderAndDrinkBeer($timeToGoHome);  // So we make the function call itself again!
    } else {  // Aw, snap!  It is time :S
        break; // Let's go home :(
    }
}

现在我们只希望您没有喝足够的啤酒而喝得酩酊大醉,以至于您的妻子会让您睡在沙发上,而不管您是否在家准时 -.-

但是,是的,递归就是这样进行的。

Recursion is something that repeats itself. Like a function that calls itself from within itself. Let me demonstrate in a somewhat pseudo example:

Imagine you're out with your buddies drinking beer, but your wife is going to give you hell if you don't come home before midnight. For this purpose, let's create the orderAndDrinkBeer($time) function where $time is midnight minus the time it takes you to finish your current drink and get home.

So, arriving at the bar, you order your first beer and commence the drinking:

$timeToGoHome = '23';  // Let's give ourselves an hour for last call and getting home

function orderAndDrinkBeer($timeToGoHome) {  // Let's create the function that's going to call itself.
    $beer = New Beer();  // Let's grab ourselves a new beer
    $currentTime = date('G'); // Current hour in 24-hour format

    while ($beer->status != 'empty') {  // Time to commence the drinking loop
        $beer->drink();  // Take a sip or two of the beer(or chug if that's your preference)
    }

    // Now we're out of the drinking loop and ready for a new beer

    if ($currentTime < $timeToGoHome) { // BUT only if we got the time
        orderAndDrinkBeer($timeToGoHome);  // So we make the function call itself again!
    } else {  // Aw, snap!  It is time :S
        break; // Let's go home :(
    }
}

Now let's just hope you weren't able to drink enough beer to become so intoxicated that your wife is going to make you sleep on the couch regardless of being home on time -.-

But yeah, that's pretty much how recursion goes.

何以畏孤独 2024-09-05 05:48:06

它是一个调用自身的函数。它对于遍历某些重复的数据结构(例如树)很有用。 HTML DOM 是一个典型的例子。

javascript 中的树结构示例和“遍历”树的递归函数。

    1
   / \
  2   3
     / \
    4   5

--

var tree = {
  id: 1,
  left: {
    id: 2,
    left: null,
    right: null
  },
  right: {
    id: 3,
    left: {
      id: 4,
      left: null,
      right: null
    },
    right: {
      id: 5,
      left: null,
      right: null
    }
  }
};

为了遍历树,我们重复调用相同的函数,将当前节点的子节点传递给相同的函数。然后我们再次调用该函数,首先调用左侧节点,然后调用右侧节点。

在这个例子中,我们将获得树的最大深度。

var depth = 0;

function walkTree(node, i) {

  //Increment our depth counter and check
  i++;
  if (i > depth) depth = i;

  //call this function again for each of the branch nodes (recursion!)
  if (node.left != null) walkTree(node.left, i);
  if (node.right != null) walkTree(node.right, i);

  //Decrement our depth counter before going back up the call stack
  i--;
}

最后我们调用函数

alert('Tree depth:' + walkTree(tree, 0));

理解递归的一个好方法是在运行时单步执行代码。

Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.

An example of a tree structure in javascript and a recursive function to 'walk' the tree.

    1
   / \
  2   3
     / \
    4   5

--

var tree = {
  id: 1,
  left: {
    id: 2,
    left: null,
    right: null
  },
  right: {
    id: 3,
    left: {
      id: 4,
      left: null,
      right: null
    },
    right: {
      id: 5,
      left: null,
      right: null
    }
  }
};

To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.

In this example, we'll get the maximum depth of the tree

var depth = 0;

function walkTree(node, i) {

  //Increment our depth counter and check
  i++;
  if (i > depth) depth = i;

  //call this function again for each of the branch nodes (recursion!)
  if (node.left != null) walkTree(node.left, i);
  if (node.right != null) walkTree(node.right, i);

  //Decrement our depth counter before going back up the call stack
  i--;
}

Finally we call the function

alert('Tree depth:' + walkTree(tree, 0));

A great way of understanding recursion is to step through the code at runtime.

剩余の解释 2024-09-05 05:48:06

简单来说:递归函数就是调用自身的函数。

Simply put: a recursive function is a function that calls itself.

橪书 2024-09-05 05:48:06

这非常简单,当一个函数调用自身来完成未定义且有限时间的任务时。我自己的代码中的一个示例,用于填充多级类别树的函数

function category_tree($parent=0,$sep='')
{
    $q="select id,name from categorye where parent_id=".$parent;
    $rs=mysql_query($q);
    while($rd=mysql_fetch_object($rs))
    {
        echo('id.'">'.$sep.$rd->name.'');
        category_tree($rd->id,$sep.'--');
    }
}

It is very simple, when a function calls itself for accomplishing a task for undefined and finite number of time. An example from my own code, function for populating a with multilevel category tree

function category_tree($parent=0,$sep='')
{
    $q="select id,name from categorye where parent_id=".$parent;
    $rs=mysql_query($q);
    while($rd=mysql_fetch_object($rs))
    {
        echo('id.'">'.$sep.$rd->name.'');
        category_tree($rd->id,$sep.'--');
    }
}
意中人 2024-09-05 05:48:06

递归是“再次做这件事直到完成”的一种奇特方式。

有两件重要的事情需要具备:

  1. 基本情况 - 您有一个要实现的目标。
  2. 测试 - 如何知道您是否到达目的地。

想象一个简单的任务:按字母顺序对一堆书进行排序。一个简单的过程就是对前两本书进行排序。现在,递归部分来了:还有更多的书吗?如果是这样,请再做一次。 “再做一次”就是递归。 “还有更多的书吗”是测试。 “不,不再有书了”是基本情况。

Recursion is a fancy way of saying "Do this thing again until its done".

Two important things to have:

  1. A base case - You've got a goal to get to.
  2. A test - How to know if you've got to where you're going.

Imagine a simple task: Sort a stack of books alphabetically. A simple process would be take the first two books, sort them. Now, here comes the recursive part: Are there more books? If so, do it again. The "do it again" is the recursion. The "are there any more books" is the test. And "no, no more books" is the base case.

想你的星星会说话 2024-09-05 05:48:06

递归是循环的替代方案,它们很少会给您的代码带来更多的清晰性和优雅性。 Progman 的回答给出了一个很好的例子,如果他不使用递归,他将被迫跟踪他当前所在的目录(这称为状态),递归允许他使用堆栈(变量所在的区域)进行簿记并存储方法的返回地址)

标准示例阶乘和斐波那契对于理解概念没有用,因为它们很容易被循环替换。

Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

情话墙 2024-09-05 05:48:06

当我学习自己在这里时,我找到了最好的解释:http://www .elated.com/articles/php-recursive-functions/

这是因为一件事:

调用函数时在内存中创建(创建新实例)

所以递归函数不是调用它自己,而是调用其他实例 - 所以它不是内存中的一个函数在做一些魔法。它在内存中的几个实例返回自己的一些值 - 例如,当函数 a 调用函数 b 时,这种行为是相同的。您有两个实例,以及递归函数调用其自身的新实例。

试着用纸上的实例来描绘记忆——这会很有意义。

Best explanation I have found when I was learning that myself is here:http://www.elated.com/articles/php-recursive-functions/

Its because one thing:

The function when its called is created in memory (new instance is created)

So the recursive function IS NOT CALLLING ITSELF, but its calling other instance - so its not one function in memory doing some magic. Its couple of instances in memory which are returning themselves some values - and this behavior is the same when for example function a is calling function b. You have two instances as well as if recursive function called new instance of itself.

Try draw memory with instances on paper - it will make sense.

调妓 2024-09-05 05:48:06

遍历目录树就是一个很好的例子。您可以执行类似的操作来处理数组。这是一个非常简单的递归函数,它简单地处理一个字符串、一个简单的字符串数组或任何深度的嵌套字符串数组,将字符串中的“hello”实例替换为“goodbye”或数组的值或任何子数组:

function replaceHello($a) {
    if (! is_array($a)) {
        $a = str_replace('hello', 'goodbye', $a);
    } else {
        foreach($a as $key => $value) {
            $a[$key] = replaceHello($value);
        }
    }
    return $a
}

它知道何时退出,因为在某些时候,它正在处理的“事物”不是数组。例如,如果您调用replaceHello('hello'),它将返回'goodbye'。如果你向它发送一个字符串数组,尽管它会为数组的每个成员调用一次自身,然后返回处理后的数组。

Walking through a directory tree is a good example. You can do something similar to process an array. Here is a really simple recursive function that simply processes a string, a simple array of strings, or a nested array of strings of any depth, replacing instances of 'hello' with 'goodbye' in the string or the values of the array or any sub-array:

function replaceHello($a) {
    if (! is_array($a)) {
        $a = str_replace('hello', 'goodbye', $a);
    } else {
        foreach($a as $key => $value) {
            $a[$key] = replaceHello($value);
        }
    }
    return $a
}

It knows when to quit because at some point, the "thing" it is processing is not an array. For example, if you call replaceHello('hello'), it will return 'goodbye'. If you send it an array of strings, though it will call itself once for every member of the array, then return the processed array.

寂寞美少年 2024-09-05 05:48:06

如果您在 Anthony Forloney 的示例中添加某个值(例如“1”),一切都会很清楚:

function fact(1) {
  if (1 === 0) { // our base case
  return 1;
  }
  else {
  return 1 * fact(1-1); // <--calling itself.
  }
}

原始:

function fact($n) {
  if ($n === 0) { // our base case
    return 1;
  }
  else {
  return $n * fact($n-1); // <--calling itself.
  }
}

If you add a certain value (say, "1") to Anthony Forloney's example, everything would be clear:

function fact(1) {
  if (1 === 0) { // our base case
  return 1;
  }
  else {
  return 1 * fact(1-1); // <--calling itself.
  }
}

original:

function fact($n) {
  if ($n === 0) { // our base case
    return 1;
  }
  else {
  return $n * fact($n-1); // <--calling itself.
  }
}
依 靠 2024-09-05 05:48:06

基本上就是这个。它不断调用自己直到完成

void print_folder(string root)
{
    Console.WriteLine(root);
    foreach(var folder in Directory.GetDirectories(root))
    {
        print_folder(folder);
    }
}

也适用于循环!

void pretend_loop(int c)
{
    if(c==0) return;
    print "hi";
    pretend_loop(c-);
}

您也可以尝试用谷歌搜索它。请注意“您的意思是”(单击它...)。 http://www.google.com/search?q=recursion&spell= 1

Basically this. It keeps calling itself until its done

void print_folder(string root)
{
    Console.WriteLine(root);
    foreach(var folder in Directory.GetDirectories(root))
    {
        print_folder(folder);
    }
}

Also works with loops!

void pretend_loop(int c)
{
    if(c==0) return;
    print "hi";
    pretend_loop(c-);
}

You can also trying googling it. Note the "Did you mean" (click on it...). http://www.google.com/search?q=recursion&spell=1

落花浅忆 2024-09-05 05:48:06

这是阶乘与递归的一个非常简单的示例:

阶乘是一个非常简单的数学概念。他们写得像5!这意味着 5 * 4 * 3 * 2 * 1。所以 6!是 720 和 4!是 24。

function factorial($number) { 

    if ($number < 2) { 
        return 1; 
    } else { 
        return ($number * factorial($number-1)); 
    } 
}

希望这对您有用。 :)

This is a very simple example of factorial with Recursion:

Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.

function factorial($number) { 

    if ($number < 2) { 
        return 1; 
    } else { 
        return ($number * factorial($number-1)); 
    } 
}

hope this is usefull for you. :)

岁月染过的梦 2024-09-05 05:48:06

它是一个简单的递归示例(Y)

<前><代码>

It work a simple example recursive (Y)

<?php 


function factorial($y,$x) { 

    if ($y < $x) { 
        echo $y; 
    } else { 
        echo $x; 
        factorial($y,$x+1);
    } 
}

$y=10;

$x=0;
factorial($y,$x);

 ?>
何以畏孤独 2024-09-05 05:48:06

这是一个实际的例子(已经有几个很好的例子了)。我只是想添加一个对几乎所有开发人员都有用的功能。

在某些时候,开发人员需要像 API 或某种类型的对象或数组的响应一样解析对象。

最初调用此函数是为了解析一个可能只包含参数的对象,但如果该对象还包含其他对象或数组怎么办?这需要解决,并且在大多数情况下,基本函数已经做到了这一点,因此该函数只需再次调用自身(在确认键或值是对象或数组之后)并解析这个新对象或数组。最终返回的是一个字符串,它在一行上单独创建每个参数以提高可读性,但您可以轻松地将值记录到日志文件或插入数据库或其他任何内容。

我添加了 $prefix 参数来使用父元素来帮助描述结束变量,以便我们可以看到该值属于什么内容。它不包括空值之类的内容,但可以从此示例中进行修改。

如果你有对象:

$apiReturn = new stdClass();
$apiReturn->shippingInfo = new stdClass();
$apiReturn->shippingInfo->fName = "Bill";
$apiReturn->shippingInfo->lName = "Test";
$apiReturn->shippingInfo->address1 = "22 S. Deleware St.";
$apiReturn->shippingInfo->city = "Chandler";
$apiReturn->shippingInfo->state = "AZ";
$apiReturn->shippingInfo->zip = 85225;
$apiReturn->phone = "602-312-4455";
$apiReturn->transactionDetails = array(
    "totalAmt" => "100.00",
     "currency" => "USD",
     "tax" => "5.00",
     "shipping" => "5.00"
);
$apiReturn->item = new stdClass();
$apiReturn->item->name = "T-shirt";
$apiReturn->item->color = "blue";
$apiReturn->item->itemQty = 1;

并使用:

var_dump($apiReturn);

它将返回:

对象(stdClass)#1 (4) { ["shippingInfo"]=>对象(stdClass)#2 (6) { ["fName"]=> string(4) "比尔" ["lName"]=> string(4) "测试" ["地址1"]=> string(18) “22 S. Delware St.” [“城市”]=> string(8) "钱德勒" ["state"]=>字符串(2)“AZ”[“zip”]=> int(85225) } ["电话"]=>字符串(12) "602-312-4455" ["交易详情"]=>数组(4) { ["totalAmt"]=>;字符串(6)“100.00”[“货币”]=> string(3) "美元" ["税"]=> string(4) "5.00" ["运费"]=> string(4) "5.00" } ["item"]=>;对象(stdClass)#3 (3) { ["name"]=> string(7) "T 恤" ["颜色"]=>字符串(4)“蓝色”[“itemQty”]=> int(1) } }

下面是将其解析为每个参数都带有换行符的字符串的代码:

function parseObj($obj, $prefix = ''){
    $stringRtrn = '';
    foreach($obj as $key=>$value){
        if($prefix){
            switch ($key) {
                case is_array($key):
                    foreach($key as $k=>$v){
                        $stringRtrn .= parseObj($key, $obj);
                    }
                    break;
                case is_object($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        default:
                            $stringRtrn .= $prefix ."_". $key ." = ". $value ."<br>";
                            break;
                    }
                    break;
            }
        } else { // end if($prefix)
            switch($key){
                case is_array($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                case is_object($key):

                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;                      
                        default:
                            $stringRtrn .= $key ." = ". $value ."<br>";
                            break;
                    } // end inner switch 
            } // end outer switch
        } // end else
    } // end foreach($obj as $key=>$value)
    return $stringRtrn;
} // END parseObj()

这将返回对象,如下所示:

shippingInfo_fName = Bill
shippingInfo_lName = Test
shippingInfo_address1 = 22 S. Deleware St.
shippingInfo_city = Chandler
shippingInfo_state = AZ
shippingInfo_zip = 85225
phone = 602-312-4455
transactionDetails_totalAmt = 100.00
transactionDetails_currency = USD
transactionDetails_tax = 5.00
transactionDetails_shipping = 5.00
item_name = T-shirt
item_color = blue
item_itemQty = 1

我执行了嵌套 switch 语句以避免与<代码>如果。 。 。否则的话。 。 。 else,但几乎一样长。如果有帮助,只需询问 if 条件,我可以将它们粘贴给需要的人。

Here is a practical example (there are several good ones already). I just wanted to add one that is useful to almost any developer.

At some point, developers will need to parse an object as with a response from an API or some type of object or array.

This function is initially called to parse an object which may just contain parameters, but what if the object also contains other objects or arrays? This will need to be addressed, and for the most part the basic function already does this, so the function just calls itself again (after confirming that the key or value is either an object or an array) and parses this new object or array. Ultimately what is returned is a string that creates each parameter on a line by itself for readability, but you could just as easily log the values to a log file or insert into a DB or whatever.

I added the $prefix parameter to use the parent element to help describe the end variable so that we can see what the value pertains to. It doesn't include things like null values, but this can be amended from this example.

If you have the object:

$apiReturn = new stdClass();
$apiReturn->shippingInfo = new stdClass();
$apiReturn->shippingInfo->fName = "Bill";
$apiReturn->shippingInfo->lName = "Test";
$apiReturn->shippingInfo->address1 = "22 S. Deleware St.";
$apiReturn->shippingInfo->city = "Chandler";
$apiReturn->shippingInfo->state = "AZ";
$apiReturn->shippingInfo->zip = 85225;
$apiReturn->phone = "602-312-4455";
$apiReturn->transactionDetails = array(
    "totalAmt" => "100.00",
     "currency" => "USD",
     "tax" => "5.00",
     "shipping" => "5.00"
);
$apiReturn->item = new stdClass();
$apiReturn->item->name = "T-shirt";
$apiReturn->item->color = "blue";
$apiReturn->item->itemQty = 1;

and use:

var_dump($apiReturn);

it will return:

object(stdClass)#1 (4) { ["shippingInfo"]=> object(stdClass)#2 (6) { ["fName"]=> string(4) "Bill" ["lName"]=> string(4) "Test" ["address1"]=> string(18) "22 S. Deleware St." ["city"]=> string(8) "Chandler" ["state"]=> string(2) "AZ" ["zip"]=> int(85225) } ["phone"]=> string(12) "602-312-4455" ["transactionDetails"]=> array(4) { ["totalAmt"]=> string(6) "100.00" ["currency"]=> string(3) "USD" ["tax"]=> string(4) "5.00" ["shipping"]=> string(4) "5.00" } ["item"]=> object(stdClass)#3 (3) { ["name"]=> string(7) "T-shirt" ["color"]=> string(4) "blue" ["itemQty"]=> int(1) } }

and here is the code to parse it into a string with a line break for each parameter:

function parseObj($obj, $prefix = ''){
    $stringRtrn = '';
    foreach($obj as $key=>$value){
        if($prefix){
            switch ($key) {
                case is_array($key):
                    foreach($key as $k=>$v){
                        $stringRtrn .= parseObj($key, $obj);
                    }
                    break;
                case is_object($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        default:
                            $stringRtrn .= $prefix ."_". $key ." = ". $value ."<br>";
                            break;
                    }
                    break;
            }
        } else { // end if($prefix)
            switch($key){
                case is_array($key):
                    $stringRtrn .= parseObj($key, $obj);
                    break;
                case is_object($key):

                    $stringRtrn .= parseObj($key, $obj);
                    break;
                default:
                    switch ($value) {
                        case is_array($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;
                        case is_object($value):
                            $stringRtrn .= parseObj($value, $key);
                            break;                      
                        default:
                            $stringRtrn .= $key ." = ". $value ."<br>";
                            break;
                    } // end inner switch 
            } // end outer switch
        } // end else
    } // end foreach($obj as $key=>$value)
    return $stringRtrn;
} // END parseObj()

This will return the object as follows:

shippingInfo_fName = Bill
shippingInfo_lName = Test
shippingInfo_address1 = 22 S. Deleware St.
shippingInfo_city = Chandler
shippingInfo_state = AZ
shippingInfo_zip = 85225
phone = 602-312-4455
transactionDetails_totalAmt = 100.00
transactionDetails_currency = USD
transactionDetails_tax = 5.00
transactionDetails_shipping = 5.00
item_name = T-shirt
item_color = blue
item_itemQty = 1

I did the nested switch statements to avoid confusion with if . . . ifelse . . . else, but it was almost as long. If it helps, just ask for the if conditionals and I can paste them for those who need it.

白况 2024-09-05 05:48:06

用于 Kaprekar 常数的递归

function KaprekarsConstant($num, $count = 1) {
    $input = str_split($num);
    sort($input);

    $ascendingInput  = implode($input);
    $descendingInput = implode(array_reverse($input));

    $result = $ascendingInput > $descendingInput 
        ? $ascendingInput - $descendingInput 
        : $descendingInput - $ascendingInput;

    if ($result != 6174) {
        return KaprekarsConstant(sprintf('%04d', $result), $count + 1);
    }

    return $count;

}

该函数不断使用计算结果调用自身,直到达到 Kaprekar 常数,此时它将返回计算的次数。

/edit 对于任何不知道 Kaprekars Constant 的人,它需要输入 4 位数字,其中至少有两个不同的数字。

Recursion used for Kaprekar's constant

function KaprekarsConstant($num, $count = 1) {
    $input = str_split($num);
    sort($input);

    $ascendingInput  = implode($input);
    $descendingInput = implode(array_reverse($input));

    $result = $ascendingInput > $descendingInput 
        ? $ascendingInput - $descendingInput 
        : $descendingInput - $ascendingInput;

    if ($result != 6174) {
        return KaprekarsConstant(sprintf('%04d', $result), $count + 1);
    }

    return $count;

}

The function keeps calling itself with the result of the calculation until it reaches Kaprekars constant, at which it will return the amount of times the calculations was made.

/edit For anyone that doesn't know Kaprekars Constant, it needs an input of 4 digits with at least two distinct digits.

难得心□动 2024-09-05 05:48:06

当某些内容包含或使用相似版本时,就会发生递归
当具体谈论计算机编程时,
当函数调用自身时,就会发生递归。

以下链接帮助我更好地理解递归,即使我认为这是迄今为止我学到的最好的链接。

它附带了一个示例来了解内部(递归)函数在执行时如何调用。

请仔细阅读这篇文章,我已经粘贴了测试程序,以防文章被扔掉。您可以在本地服务器上运行该程序以查看其运行情况。

https://www.elated.com/php-recursive-functions/

<?php

function factorial( $n ) {

  // Base case
  if ( $n == 0 ) {
    echo "Base case: $n = 0. Returning 1...<br>";
    return 1;
  }

  // Recursion
  echo "$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
  $result = ( $n * factorial( $n-1 ) );
  echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
  return $result;
}

echo "The factorial of 5 is: " . factorial( 5 );

?>

Recursion occurs when something contains, or uses, a similar version
of itself.When talking specifically about computer programming,
recursion occurs when a function calls itself.

The following link helps me to understand recursion better, even I consider this is the best so far what I've learned.

It comes with an example to understand how the inner(recursive) functions called while executing.

Please go through the article and I have pasted the test program in case if the article got trashed. You may please run the program in local server to see it in action.

https://www.elated.com/php-recursive-functions/

<?php

function factorial( $n ) {

  // Base case
  if ( $n == 0 ) {
    echo "Base case: $n = 0. Returning 1...<br>";
    return 1;
  }

  // Recursion
  echo "$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
  $result = ( $n * factorial( $n-1 ) );
  echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
  return $result;
}

echo "The factorial of 5 is: " . factorial( 5 );

?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文