Home  >  Article  >  Backend Development  >  get_term_children 源码的疑问:if ( $term_id == $child ) 自己会是自己的子项?

get_term_children 源码的疑问:if ( $term_id == $child ) 自己会是自己的子项?

WBOY
WBOYOriginal
2016-06-20 12:43:47998browse

 * @param string $term_id  ID of Term to get children.
 * @param string $taxonomy Taxonomy Name.
 * @return array|WP_Error List of Term IDs. WP_Error returned if `$taxonomy` does not exist.
 */
function get_term_children( $term_id, $taxonomy ) {
        if ( ! taxonomy_exists($taxonomy) )
                return new WP_Error('invalid_taxonomy', __('Invalid taxonomy'));

        $term_id = intval( $term_id );

        $terms = _get_term_hierarchy($taxonomy);

        if ( ! isset($terms[$term_id]) )
                return array();

        $children = $terms[$term_id];

        foreach ( (array) $terms[$term_id] as $child ) {
                 if ( $term_id == $child ) {//  自己会是自己的子项?这种假设没有必要吧?请教达人
                        continue;
                }

                if ( isset($terms[$child]) )
                        $children = array_merge($children, get_term_children($child, $taxonomy));
        }

        return $children;
}


回复讨论(解决方案)

有没有必要,要看数据是如何组织的。但你并没有给出,所以不好评价
不过仅就这个代码而言,这是必要的
if ( isset($terms[$child]) )
                        $children = array_merge($children,  get_term_children($child, $taxonomy));
get_term_children 递归调用
当 $term_id 等于 $child 时就死循环了

所以
 if ( $term_id == $child ) {
                        continue;
                }
就是非常必要的
并且从代码组织上看,这也是在确实出现了死循环后才加上的
使得代码看上去比较臃肿

是啊,初始时  $term_id !== $child,可循环过程中,有可能  $term_id == $child ,这样就出现死循环。
听君一席话,胜读十年书!
佩服

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php?修改urlNext article:小白大神,关于php创建文件