An introduction to the problem of recursive function return values in PHP is presented in the example of Ecshop infinite classification.
When Ecshop two times in the development of Product Classification index, the classification ID to obtain the top-level classification ID. The first response is recursive, so the recursive function is written as follows:
|
copy code |
function Getcattopid ($cat _id) { if ($ cat_id) { $res = Array (); $sql = ' SELECT cat_id, parent_id ' . ' From '. $GLOBALS [' ECS ']->table (' category ') . ' WHERE cat_id = '. $cat _id. ' and is_show = 1 '; $res = $GLOBALS [' db ']->getall ($sql); If ($res [0][' parent_id '] > 0) { Getcattopid ($res [0][' parent_id ']); } Else { return $res [0][' cat_id ']; } } Else { return 1; } } |
A test program, did not get the return value? The examination for a long time did not find errors, it seems the skull is broken. Today asked the God of the gods (a good friend), he helped me to answer, modified as follows:
|
copy code |
function Getcattopid ($cat _id) { if ($ cat_id) { $res = Array (); $sql = ' SELECT cat_id, parent_id ' . ' From '. $GLOBALS [' ECS ']->table (' category ') . ' WHERE cat_id = '. $cat _id. ' and is_show = 1 '; $res = $GLOBALS [' db ']->getall ($sql); If ($res [0][' parent_id '] > 0) { return getcattopid ($res [0][' parent_id ']);//modify, write a return, let function return value } else { return $res [0][' cat_id ']; } Else { return 1; } } |
The function is written internally, and even if it returns, it just returns to the inside of the function, so there is a layer of main function outside, must return again
http://www.bkjia.com/PHPjc/631608.html www.bkjia.com true http://www.bkjia.com/PHPjc/631608.html techarticle An introduction to the problem of recursive function return values in PHP is presented in the example of Ecshop infinite classification. In the Ecshop two times in the development of product Classification index, according to the classification of the ID to get belong to ...