The first time you write a recursive function, please take a look at what is wrong and how to handle it
Source: Internet
Author: User
The first time you write a recursive function, please check the function & nbsp; check ($ num) {& nbsp; & nbsp; $ sn = $ write the recursive function for the first time. Please check the error.
Function check ($ num ){
$ Sn = $ num;
$ SQL = "select * from 'a _ dinghuo 'Where 'num' = '$ num '";
$ Q = mysql_query ($ SQL );
$ Row = mysql_num_rows ($ q );
If ($ row = 1 ){
$ Sn = ($ num + 1 );
Check ($ num + 1 );
}
Return $ sn;
}
My idea is that if the database itself has this value, then this value is + 1
However, I finally returned the original parameter... where is the error?
Thank you!
------ Solution --------------------
Because there is no such number in your database.
------ Solution --------------------
Function check ($ num ){
$ Sn = $ num;
$ SQL = "select * from 'a _ dinghuo 'Where 'num' = '$ num '";
$ Q = mysql_query ($ SQL );
$ Row = mysql_num_rows ($ q );
If ($ row = 1 ){
$ Sn = check ($ num + 1); // modify here
}
Return $ sn;
}
But here we can't see the role of recursion.
------ Solution --------------------
If there is one, your recursion will lead to an endless loop.
------ Solution --------------------
It is indeed an endless loop! Add a recursive jump! For example, if the number is determined twice or exceeds a certain number, the system jumps out!
Function check ($ num ){
Static $ array = array );
$ Sn = $ num;
If (in_array ($ num, $ array )){
Print $ num .'';
$ Sn = ($ num + 1 );
Check ($ num + 1 );
}
Return $ sn;
}
Print check (3 );
?>
Output: 3 4 5 6 7 8 9 10 4
If your database has a large number of num records and is a sequence, you will find that your mysql statement runs very high.
------ Solution --------------------
It's not going to take a closer look.
$ Num + 1 ......
------ Solution --------------------
$ SQL = "select * from 'a _ dinghuo 'Where 'num' = '$ num '";
Check ($ num + 1 );
$ Num should be of the same type ..
------ Solution --------------------
Function check ($ num ){
Static $ sn;
$ SQL = "select * from 'a _ dinghuo 'Where 'num' = '$ num '";
$ Q = mysql_query ($ SQL );
$ Row = mysql_num_rows ($ q );
If ($ row = 1 ){
$ Sn. = ($ num + 1 );
Check ($ num + 1 );
}
Return $ sn;
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service