Search Category.

A

Anonymous

Guest
An array of "categories" is given:

Code:
    $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.
 
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:
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.
 
Back
Top