Jump to content

Recommended Posts

An array of "categories" is given:

    $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.

Link to comment
https://forums.phpfreaks.com/topic/312122-search-category/
Share on other sites

Use a recursive function to search subcategories until found

(Pseudocode ti illustrate the logic...)

function searchCategories (category, id, title)
{
    foreach (category as cat) {
        if (this has the id we want) 
            set title value
        else 
            searchCategories(children, id, title)        // calls itself to search sub categories
        end if
    }
}

My test...


$category = $categories;

for ($searchfor = 1; $searchfor <= 8; $searchfor++) {
    $title='Not found';
    searchCategories($category, $searchfor, $title);
    echo "$searchfor - $title<br>";
}

/*
RESULTS
1 - Pants
2 - Boots
3 - Leather
4 - Textile
5 - Sneakers
6 - Sort
7 - Balls
8 - Not found                                    
*/

 

Link to comment
https://forums.phpfreaks.com/topic/312122-search-category/#findComment-1584350
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.