递归易绕,以供参考
例一 :阶乘
function factorial($n) { if ($n > 1) { return $n * factorial($n -1); } else { return 1; } } //4的阶乘输出24 echo factorial(4);
例二:获取树形菜单
//递归函数,获取树形菜单数据,(参数为父节点id、包含所有数据的数组、用来存放子菜单的数组) private function funcGetMenuData($id, $dataArr, &$treeArr) { //数组索引号 $arrIndex = -1; foreach ($dataArr as $v) { if ($v["pid"] == $id ) { //数组索引号从0开始 $arrIndex++; $treeArr[$arrIndex]["id"] = $v["id"]; $treeArr[$arrIndex]["text"] = $v["tree_text"]; $treeArr[$arrIndex]["state"] = $v["tree_state"]; if (isset($v["tree_url"])) { $treeArr[$arrIndex]["attributes"]["url"] = $v["tree_url"]; } //定义children元素为一个数组 $treeArr[$arrIndex]["children"] = []; //如果没有子菜单 if (!$this->hasChildren($v["id"], $dataArr)) { //删除children数组元素 unset($treeArr[$arrIndex]["children"]); continue; //如果有子菜单 } else { //递归使用自身函数,(参数为此菜单的id、包含所有数据的数组、用来存放子菜单的数组) $this->funcGetMenuData($v["id"], $dataArr, $treeArr[$arrIndex]["children"]); } } } }
例三:从一个数组中获取某个查询内容的"父元素"数组
//从一个数组中获取某个查询内容的父元素数组 // (版本一) function getParentElementFromArray($array, $search) { static $parent = null; if (is_array($array)) { if (in_array($search, $array)) { $parent = $array; } else { foreach ($array as $k=>$data) { getParentElementFromArray($data, $search); } } } return $parent; } //(版本二) 上面方法的改进,比上面节省资源,查找到则停止 function getParentElementFromArray($array, $search) { static $parent = null; static $find = false; if (is_array($array)) { if (in_array($search, $array)) { $parent = $array; $find = true; } else { foreach ($array as $k=>$data) { if (!$find) { getParentElementFromArray($data, $search); } else { break; } } } } return $parent; }