2016-08-15 127 views
0

以下PHP代碼不包括Google Merchant Center中的Woocommerce類別。你如何結合in_array來縮短代碼?在PHP中組合多個陣列

// Exclude categories from my Google Product Feed 

function lw_gpf_exclude_product($excluded, $product_id, $feed_format) { 
    // Return TRUE to exclude a product, FALSE to include it, $excluded to use the default behaviour. 
    $cats = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); 
    if (in_array(60, $cats)) { 
     return TRUE; 
    } 
    if (in_array(63, $cats)) { 
     return TRUE; 
    } 
    if (in_array(88, $cats)) { 
     return TRUE; 
    } 
    if (in_array(89, $cats)) { 
     return TRUE; 
    } 
    return $excluded; 
} 
add_filter('woocommerce_gpf_exclude_product', 'lw_gpf_exclude_product', 11, 3); 
+0

[http://php.net/manual/en/function.array-intersect.php](http://php。淨/手動/ EN/function.array-intersect.php) – cske

回答

2

如果只有一個值就足以返回true,則可以相交兩個陣列,並且如果所得到的陣列具有尺寸(具有元素),則至少有一個值存在於兩個陣列。

return count(array_intersect([60, 63, 88, 89], $cats)) > 0; 
0

使用array_intersect功能的解決方案:

... 
if (array_intersect([60, 63, 88, 89], $cats)){ 
    return TRUE; 
} 
0

嘗試。

return !empty(array_intersect(array(60,63,88,89),$cats)); 
0

使用

in_array_any
功能這樣使代碼更短

 

    function in_array_any($needles, $haystack) { 
     return !!array_intersect($needles, $haystack); 
    } 

    if(in_array_any([60,63,88,89], $cats)){ 
     return TRUE; 
    }