recursion - Laravel recursively get all offsprings of a taxonomy -
i have table called taxonomies stores taxonomies of products ecommerce site. how table looks like:
+--------------+------------------+------+-----+---------+----------------+ | field | type | null | key | default | | +--------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | no | pri | null | auto_increment | | name | varchar(20) | no | uni | null | | | parent_id | int(10) unsigned | yes | mul | null | | | num_products | smallint(6) | no | | 0 | | +--------------+------------------+------+-----+---------+----------------+
now given taxonomy id, how can recursively offspring ids? effort far:
public function getalltaxonomyoffspringids($parent_id, $offspring_ids = array()) { $taxonomy = taxonomy::find($parent_id); if (!is_null($taxonomy)) { $first_generation_ids = $taxonomy->subtaxonomies()->lists('id'); $offspring_ids = array_merge($offspring_ids, $first_generation_ids); if (count($first_generation_ids) > 0) { foreach ($first_generation_ids $child_id) { self::getalltaxonomyoffspringids($child_id, $offspring_ids); } // foreach ($first_generation_ids $child_id) { // $child_taxonomy = taxonomy::find($child_id); // if (!is_null($child_taxonomy)) { // $second_generation_ids = $child_taxonomy->subtaxonomies()->lists('id'); // $offspring_ids = array_merge($offspring_ids, $second_generation_ids); // if (count($second_generation_ids)) { // } // } // } } } homecoming $offspring_ids; }
but gives me ids of first generation children...
this width first tree traversal algorithm, , here's code i've managed figure out how to:
public function gettaxonomychildren($id) { $taxonomy = taxonomy::find($id); $child_ids = array(); if (!is_null($taxonomy)) { $child_ids = $taxonomy->subtaxonomies()->lists('id'); } homecoming $child_ids; } public function getalltaxonomyoffspringids($parent_id, $offspring_ids = array()) { $child_ids = self::gettaxonomychildren($parent_id); $offspring_ids = array_merge($offspring_ids, $child_ids); while (count($child_ids) > 0) { $temp_ids = array(); foreach ($child_ids $child_id) { $temp_ids = array_merge($temp_ids, self::gettaxonomychildren($child_id)); } $child_ids = $temp_ids; $offspring_ids = array_merge($offspring_ids, $child_ids); } homecoming $offspring_ids; }
laravel recursion
No comments:
Post a Comment