Search Category.

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 9
Joined: Thu Dec 17, 2020 12:31 am

Wed Feb 10, 2021 1:39 am

An array of "categories" is given:

Code: Select all

    
    $categories = array(
        array("id" => 1, "title" => "Pants", "children" => array(
            array("id" => 2,
                "title" => "Boots",
                "children" => array(
                    array("id" => 3, "title" => "Leather"),
                    array("id" => 4, "title" => "Textile"),
                ),
            ),
            array("id" => 5, "title" => "Sneakers"),
        ),
        ),
        array(
            "id" => 6,
            "title" => "Sort",
            "children" => array(
                array(
                    "id" => 7,
                    "title" => "Balls",
                ),
            ),
        ),
    );
    
I need to write a function searchCategory ($categories, $id) that returns the name of the category by the category ID.

Help me please.
simonbrahan
php-forum Fan User
php-forum Fan User
Posts: 104
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Wed Feb 10, 2021 3:01 am

This is a recursive problem; your structure can contain itself, so your code has to occasionally treat a small chunk of the data as a whole structure again.

You code must do the following:
  • Look at each category in turn.
  • If the ID matches, return the name there.
  • If the category has children, search those children using this process.
  • If the search above found your match, return it.
  • Otherwise, continue searching this level of categories.
  • If you get to the end without finding your ID, return false.
Your code could look like this:

Code: Select all

function searchCategory($categories, $id)
{
    foreach ($categories as $category) {
        if ($category["id"] == $id) {
            return $category["title"];
        }

        if (!isset($category["children"])) {
            continue;
        }

        $found_name = searchCategory($category["children"], $id);

        if ($found_name) {
            return $found_name;
        }
    }

    return false;
}
Note the call to searchCategory($category["children"], $id); this is your recursion, your function is calling itself with different values. This is a useful approach when you're working with nested structures like this.
User avatar
Drummer
New php-forum User
New php-forum User
Posts: 9
Joined: Thu Dec 17, 2020 12:31 am

Wed Feb 10, 2021 11:04 pm

Thank you very much!
User avatar
GeorgeLoo
New php-forum User
New php-forum User
Posts: 5
Joined: Tue Aug 01, 2017 4:19 am

Tue Mar 23, 2021 8:27 am

Thanks for that script
Post Reply