freaky
freaky

Reputation: 1010

PHP - recursive function foreach

I would to create a recursive function in order to retrieve data from an array and to organize then. However I have some difficulties to create the right logic. The principle must be apply to any sub level until it ends or nothing is found. I want to prevent this kind of code by repeating a foreach inside a 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;

                        }
                    }

                }
            }
        }

    }
}

Upvotes: 1

Views: 1263

Answers (1)

Ranjeet Singh
Ranjeet Singh

Reputation: 924

May be this code help you to get idea for formatting your desired array format.

<?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;
    }
}
?>

I use this code for my previous project for generating categories that upto n-th level

Upvotes: 1

Related Questions