ElijahLoop Posted February 10, 2021 Share Posted February 10, 2021 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. Quote Link to comment https://forums.phpfreaks.com/topic/312122-search-category/ Share on other sites More sharing options...
Barand Posted February 10, 2021 Share Posted February 10, 2021 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 */ Quote Link to comment https://forums.phpfreaks.com/topic/312122-search-category/#findComment-1584350 Share on other sites More sharing options...
ElijahLoop Posted February 11, 2021 Author Share Posted February 11, 2021 Thank you very much! Quote Link to comment https://forums.phpfreaks.com/topic/312122-search-category/#findComment-1584370 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.