PHP - 递归函数foreach

时间:2016-03-16 16:05:54

标签: php function recursion

我想创建一个递归函数,以便从数组中检索数据然后进行组织。 但是我在创建正确的逻辑方面遇到了一些困难。该原则必须适用于任何子级别,直到它结束或找不到任何内容。 我想通过在foreach中重复一个foreach来阻止这种代码...:

$cats = get_categories($args);  
$categories = array();
foreach($cats as $cat){
    $parent = $cat->category_parent;
    if ($parent) {
            $categories['child'][$parent][$cat->cat_ID] = $cat->name;
        } else {
            $categories['parent'][$cat->cat_ID] = $cat->name;
        }
    }
}

if (isset($categories['parent']) && !empty($categories['parent'])) {
        foreach($categories['parent'] as $id => $cat){

            $new_cats[$id]['title'] = $cat;

            if (isset($categories['child'][$id])) {
                foreach($categories['child'][$id] as $child_id => $child_cat){

                    $new_cats[$child_id]['title'] = $child_cat;
                    $new_cats[$child_id]['parent_id'] = $id;

                    if (isset($categories['child'][$child_id])) {
                        foreach($categories['child'][$child_id] as $sub_child_id => $sub_child_cat){

                            $new_cats[$sub_child_id]['title'] = $sub_child_cat;
                            $new_cats[$sub_child_id]['parent_id'] = $child_id;

                        }
                    }

                }
            }
        }

    }
}

1 个答案:

答案 0 :(得分:1)

可能是这段代码可以帮助您了解格式化所需的数组格式。

<?php
// Main function
function BuildArr($arr)
{
    $formattedArr = array();
    if(!empty($arr))
    {
        foreach($arr as $val)
        {
            if($val['has_children'])
            {
                $returnArr = SubBuildArr($val['children']);  // call recursive function
                if(!empty($rs))
                {
                    $formattedArr[] = $returnArr;
                }
            }
            else
            {
                $formattedArr[] = $val;         
            }
        }
    }
    return $formattedArr;
}

// Recursive Function( Build child )
function SubBuildArr($arr)
{
    $sub_fortmattedArr = array();
    if(!empty($arr))
    {
        foreach($arr as $val)
        {
            if($val['has_children'])
            {
                $response = SubBuildArr($val['children']); // call recursive
                if(!empty($response))
                {
                    $sub_fortmattedArr[] = $response;
                }
            }
            else
            {
                $sub_fortmattedArr[] = $arr;
            }
        }
        return  $sub_fortmattedArr;
    }
}
?>

我将此代码用于我之前的项目,用于生成最高级别的类别