遞迴函式使用例項
阿新 • • 發佈:2018-11-02
一.建立遞迴陣列
//$fid 父id $v['id'] 子id $v['child'] 子id陣列
//$cate 要迴圈的一維陣列
function digui($cate, $fid = 0){
foreach ($cate as $v)
{
if ($v['fid'] == $fid)
{
$v['child'] = digui($cate, $v['id']);
$arr[] = $v;
}
}
return $arr;
}
digui($arrAll);
二.遞迴陣列轉一維陣列
-
1.
$arrayiter = new RecursiveArrayIterator($arrAll);
$iteriter = new RecursiveIteratorIterator($arrayiter);
//直接列印即可按照橫向順序打印出來
foreach ($iteriter as $key => $val){
echo $key.'=>'.$val;
}
2.
function get_array_elems($arrResult, $where = "array" ){
while(list($key,$value)=each($arrResult)){
if (is_array($value)){
get_array_elems($value, $where."[$key]");
}
else {
for ($i=0; $i<count($value);$i++){
echo $where."[$key]=".$value."<BR>\n";
}
}
}
}
get_array_elems($arrAll );
三 順序輸出遞迴陣列
function get_cate(&$data=array(),$fid=0,$i=-1){
$i++;
$sql="select id,fid from toa_module where fid='$fid'";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)){
$row['num']=$i;
$data[]=$row;
get_cate($data,$row['id'],$i);
}
return $data;
}