我有一个算法可以在 WordPress 中进行一些产品类别计算...该算法感兴趣的部分如下:
foreach ( $product_categories as $product_category ) {
if ( check_children( $product_category->term_id, $product_ids ) ) {
// Here we perform some calculations when $product_category->term_id's children categories (their IDs actually) aren't included in the array (of IDs) $product_ids
}
}
check_children
功能是这样的:
function check_children( $parent, $term_ids = array() ) {
$is_latest_child = true;
$children = get_term_children( $parent, 'product_cat' ); // For those not familiar with WP, this function returns an array of category IDs that are children of the "$parent" category at question
if ( count( $children ) > 0 ) { // First of all, this count is obsolete, isn't it? I mean, foreach below already takes care of the case when $children is empty, isn't this so?
foreach ( $children as $child ) {
if ( in_array( $child, $term_ids ) ) { // So all that's needed is at least one child category of the $parent at question to be included in the array of "prohibited" categories in $term_ids
$is_latest_child = false;
break;
}
}
}
return $is_latest_child;
}
所以我想要的是优化,或者更好的是使用
check_children
完全消除 array_intersect
的使用...但我对参数的正确顺序有点困惑。让我更具体地说:
我打算更换这个:
if ( check_children( $product_category->term_id, $product_ids ) ) {
有了这个(我更倾向于这个):
if ( count( array_intersect( get_term_children( $product_category->term_id, 'product_cat' ), $product_ids ) ) === 0 ) {
或者这是正确的吗:
if ( count( array_intersect( $product_ids, get_term_children( $product_category->term_id, 'product_cat' ) ) ) === 0 ) {
或者这实际上并不重要?请记住,我想用这个排序器“解决方法”替换我已经存在的算法。
(我在第二个代码块的评论中有一两个问题。你能也回答一下吗?)
TIA。
我想说,
check_children()
功能已经优化得相当好。有条件破坏的循环最有可能超越 array_intersect()
或 array_diff()
调用,因为这些数组函数的设计目的不是在遍历整个有效负载之前停止迭代。
我想如果我必须调整这个功能,它会看起来像这样:
function isLatestChild(int $parent, array $term_ids = []): bool
{
if ($term_ids) { // only bother iterating children if there is a haystack
foreach (get_term_children($parent, 'product_cat') as $child) {
if (in_array($child, $term_ids)) {
return false;
}
}
}
return true;
}