php - Recursive function to get the parent caegory description -


i have created recursive function, , need parent category description , term_id of product.

function desc_pro($parent) {     $term = get_term_by('parent', $parent, 'product_cat');     $description = $term->description;      while($description == null) {         $desc = desc_pro($term->parent);         return $desc;     }     return $description; } 

now when run code, correct description. if remove of return not work. shows blank. (this okay? think code wrong?)

second: need term_id , when create array, send sub category ids well. wrong. need id has description.

i think code wrong? or there other problem?

this array me: (what send parent category php page. call function get_desc(48);)

it give me first object, have test description available or not? if yes stop , return description , it's term_id. if not available grab parent id , check again. continues, until description found.

stdclass object (     [term_id] => 48     [name] => cereal     [slug] => cereal     [term_group] => 0     [term_taxonomy_id] => 49     [taxonomy] => product_cat     [description] =>      [parent] => 46     [count] => 0 )  stdclass object (     [term_id] => 46     [name] => grocery store     [slug] => grocery-store-a     [term_group] => 0     [term_taxonomy_id] => 47     [taxonomy] => product_cat     [description] => fdic, 17th street northwest, washington, dc     [parent] => 45     [count] => 0 ) 

since while loop doesn't change $description $desc, null if it's not base case , have created infinite loop.

try this:

function desc_pro($parent) {     $term = get_term_by('parent', $parent, 'product_cat');     $description = $term->description;      if( $description == null)         return desc_pro($term->parent); // recurse if not set         //$description = desc_pro($term->parent); // alternative above      return $description; // base case (when set) } 

the differences between return , assignment return. php doesn't tail call optimization it's not different, 1 not commented out looks better functional programmer.

for iterative approach while loop good:

function desc_pro($parent) {     $description = null;      while( $description == null) {         $term = get_term_by('parent', $parent, 'product_cat');         $description = $term->description;     }      return $description; // base case (when set) } 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -