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

moliu 2015-11-27 10:07:09
* @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;
}
...全文
203 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
moliu 2016-03-12
  • 打赏
  • 举报
回复

迭代,从底端到项端
$term_id,$child 参数的意义,即所代表的变量发生变化。这样理解就不纠结了
moliu 2015-11-28
  • 打赏
  • 举报
回复
是啊,初始时  $term_id !== $child,可循环过程中,有可能  $term_id == $child ,这样就出现死循环。 听君一席话,胜读十年书! 佩服
xuzuning 2015-11-28
  • 打赏
  • 举报
回复
有没有必要,要看数据是如何组织的。但你并没有给出,所以不好评价 不过仅就这个代码而言,这是必要的 if ( isset($terms[$child]) ) $children = array_merge($children, get_term_children($child, $taxonomy)); get_term_children 递归调用 当 $term_id 等于 $child 时就死循环了 所以 if ( $term_id == $child ) { continue; } 就是非常必要的 并且从代码组织上看,这也是在确实出现了死循环后才加上的 使得代码看上去比较臃肿

20,398

社区成员

发帖
与我相关
我的任务
社区描述
“超文本预处理器”,是在服务器端执行的脚本语言,尤其适用于Web开发并可嵌入HTML中。PHP语法利用了C、Java和Perl,该语言的主要目标是允许web开发人员快速编写动态网页。
phpphpstorm 技术论坛(原bbs)
社区管理员
  • 开源资源社区
  • phpstory
  • xuzuning
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧