使用array_intersect替代check_children函数的参数顺序及代码优化问题
WordPress产品分类计算代码优化与疑问解答
一、array_intersect参数顺序的问题
原check_children函数的核心逻辑是:当父分类的所有子分类ID都不在$product_ids数组中时,返回true,也就是子分类数组与$product_ids的交集为空。
你给出的两种写法:
- 写法一:
count(array_intersect(get_term_children(...), $product_ids)) === 0 - 写法二:
count(array_intersect($product_ids, get_term_children(...))) === 0
两者都是正确的,因为array_intersect的参数顺序不影响最终的交集结果——它只会返回两个数组中共同存在的元素,不管哪个数组在前,交集内容完全一致。
可以进一步优化写法:用empty()替代count() === 0,empty()判断空数组时更高效,无需计算元素个数:
if ( empty( array_intersect( get_term_children( $product_category->term_id, 'product_cat' ), $product_ids ) ) ) { // 执行计算逻辑 }
二、count($children) > 0的判断是否多余?
是的,这个判断完全多余。
原代码中,当$children为空数组时,foreach ($children as $child)本身就不会执行循环,$is_latest_child会保持初始值true,和保留count判断的逻辑结果完全一致。直接去掉这个判断,代码逻辑不受影响,还能减少不必要的条件判断:
优化后的check_children函数:
function check_children( $parent, $term_ids = array() ) { $is_latest_child = true; $children = get_term_children( $parent, 'product_cat' ); foreach ( $children as $child ) { if ( in_array( $child, $term_ids ) ) { $is_latest_child = false; break; } } return $is_latest_child; }
内容的提问来源于stack exchange,提问作者Faye D.
相关产品推荐
相关产品推荐

