php遞迴使用樣本(php遞迴函式)_PHP教程

來源:互聯網
上載者:User
//遞迴獲得角色ID字串function explodeRole($roleObj, &$resultStr){  if(0 < count($roleObj->childRoleObjArr)){    foreach($roleObj->childRoleObjArr as $childRoleObj){      if('' == $resultStr){        $resultStr .= "{$childRoleObj->id}";      }else{        $resultStr .= ", {$childRoleObj->id}";      }      explodeRole($childRoleObj, $resultStr);    }  }}//遞迴擷取級聯角色資訊數組function makeRoleRelation(&$roleObjArr){  foreach($roleObjArr as $item){    $item->childRoleObjArr = getRoleObjArrByParentId($item->id);    if(0 < count($item->childRoleObjArr)){      makeRoleRelation($item->childRoleObjArr);    }  }}//通過父角色的id擷取子角色資訊  function getRoleObjArrByParentId($parentid){  $operCOGPSTRTSysRole = new COGPSTRTSysRole();  $operCOGPSTRTSysRole->setColumn($operCOGPSTRTSysRole->getAllColumn());  $operCOGPSTRTSysRole->setWhere("parentroleid={$parentid}");  $roleObjArr = $operCOGPSTRTSysRole->convResult2ObjArr($operCOGPSTRTSysRole->selectTable());  return isset($roleObjArr)?$roleObjArr:array();}

php的遞迴函式用法

一個函數在它的函數體內調用它自身稱為遞迴調用。這種函數稱為遞迴函式。這對於程式員來說,通常有很高的實用價值,常用來將複雜的問題分解為簡單的並相同的情況,反覆做這種處理直到問題解決。

用遞迴函式與不用遞迴函式的區別

樣本一:使用靜態變數

function test(){  static $dig=0;  if($dig++<10){    echo $dig;    test();  }}test();//12345678910

樣本二:使用遞迴函式和迴圈實現字串逆轉排列

function unreverse($str){  for($i=1;$i<=strlen($str);$i++){    echo substr($str,-$i,1);  }}unreverse("abcdefg");//gfedcbcfunction reverse($str){  if(strlen($str)>0){    reverse(substr($str,1));    echo substr($str,0,1);    return;  }}reverse("abcdefg");//gfedcbc

遞迴函式很多時候我們可以迴圈替代,建議當我們不能用迴圈替代時再用,因為用迴圈我們更容易理解,更不容易出錯。

php遞迴函式 php支付遞迴函式,遞迴函式就是調用自己本身,這些函數特別適用於瀏覽動態資料結構,例如樹和列表。
幾乎沒有web應用程式要求使用複雜的資料結構

<?phpfunction reversr_r($str){if (strlen($str)>0)reverse_r(substr($str,1));echo substr($str,0,1);return;}?><?phpfunction reverse_i($str){for($i=1;$i<=strlen($str);$i++){echo substr($str,-$i,1);}}

這個程式清單中實現兩個函數,這兩個函數都可以相反的順序列印字串的內容
函數reversr_r是通過遞迴實現的,而函數reverse_i()是通過迴圈實現的

http://www.bkjia.com/PHPjc/825220.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/825220.htmlTechArticle//遞迴獲得角色ID字串function explodeRole($roleObj, lt; count($roleObj-childRoleObjArr)){ foreach($roleObj-childRoleObjArr as $childRoleObj){ if('' == $resultStr){ $resul...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.