Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Cleanup empty categories from category tree

I have created a category tree where each category contains sub-categories and each category contains its associated content. Some of the categories in this tree contain sub-categories but have no associated content. How can I clean up the category tree so that the tree structure contains only categories that have associated content, or that have sub-categories that have associated content? That is, in the category tree only paths should exist that lead to a category that has associated content.

The structure I have is an array:

[uid_of_category]
   => (array)content
      => empty
   => (array)sub_categories
      => [uid_of_category]
         => (array)content
             => empty
         => (array)sub_categories
      => [uid_of_category]
         => (array)content
             => [...associated content...]
         => (array)sub_categories
 [uid_of_category]
   => (array)content
      => empty
   => (array)sub_categories
      => [uid_of_category]
         => (array)content
             => [...associated content...]
         => (array)sub_categories
      => [uid_of_category]
         => (array)content
             => empty
         => (array)sub_categories
            => [uid_of_category]
               => (array)content
                 => [...associated content...]
            => (array)sub_categories
               ...

I tried to use a recursive function to get down to the lowest elements of the tree, but I don't know how to implement that even those elements remain in the tree that have no associated content, but whose sub-element has associated content.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Obviously, recursion will help. But let use two functions instead of one. We will use one function to determine if a category meets the conditions to be cleaned (deleted). An another function to do the clean. In this function, the param will be passed by reference (&$categories). All of this assuming the structure is an array.

cleanCategories($categories);

function cleanCategories(&$categories)
{
    foreach ($categories as $key=>&$category) {
        if (isCleanable($category)) {
            unset($categories[$key]);
        } else {
            cleanCategories($category['sub_categories']);
        }
    }
}

function isCleanable($category)
{
    if (!empty($category['content'])) {
        return false;
    }

    foreach ($category['sub_categories'] as $category) {
        if (!isCleanable($category)) {
            return false;
        }
    }

    return true;
}

From this approach, you can do a better, more effient solution.

And don't forget Stack Overflow is not a writting code service. You must think by yourself, think again, find a way (just thinking), put it in code, try the code, debug the code...

over 4 years ago · Santiago Trujillo Report

0

Tried to build an array based on the OP's post:

$arr = [
    "uid_of_category_0" => [
        "content"        => [],
        "sub_categories" => [
            "uid_of_category_0_0" => [
                "content"        => [],
                "sub_categories" => []
            ],
            "uid_of_category_0_1" => [
                "content"        => [
                    "associated_content_0_1_0",
                    "associated_content_0_1_1",
                    "associated_content_0_1_2"
                ],
                "sub_categories" => []
            ]
        ]
    ],
    "uid_of_category_1" => [
        "content"        => [],
        "sub_categories" => [
            "uid_of_category_1_0" => [
                "content"        => [
                    "associated_content_1_0_0",
                    "associated_content_1_0_1",
                    "associated_content_1_0_2"
                ],
                "sub_categories" => []
            ],
            "uid_of_category_1_1" => [
                "content"        => [],
                "sub_categories" => [
                    "uid_of_category_1_1_0" => [
                        "content"        => [
                            "associated_content_1_1_0_0",
                            "associated_content_1_1_0_1",
                            "associated_content_1_1_0_2"
                        ],
                        "sub_categories" => []
                    ]
                ]
            ]
        ]
    ],
];

This would be the code to unset all empty arrays within $arr:

function unset_empty_arrays(array $arr): array {
  foreach (array_keys($arr) as $key) {
    if (is_array($arr[$key])) {
      $arr[$key] = unset_empty_arrays($arr[$key]);
    }
    if ($arr[$key] === [] && $key === 'sub_categories') {
      unset($arr[$key]);
    }
  }
  return $arr;
}

print_r(unset_empty_arrays($arr));

Edit: added && $key === 'sub_categories'

over 4 years ago · Santiago Trujillo Report

0

This case is best solved with postorder traversal of tree.

In postorder traversal you want to do recursion over all sub-trees first. Then do required operation on the current node.

function cleanUp(&$categories) {
    if (empty($categories)) {
        //no categories, nothing to do here
        return;
    }

    foreach ($categories as $key => &$category) {
        //first clean up sub categories
        cleanUp($category['sub_categories']);
 
        if (empty($category['sub_categories']) && empty($category['content'])) {
            //If there are no sub_categories left and there is no content remove category
            unset($categories[$key]);
        }
    }
}

After doing clean up on sub categories, you know that if there are any sub categories left, they must have content or sub categories with content. So, at that point you can easily decide if current category needs to be removed.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!