PHP条件基于数组中的任何项目

时间:2013-08-30 18:36:46

标签: php conditional strip-tags

我正在使用php从一系列woocommerce(wordpress)购物车中提取类别名称,如下所示:

<?php $stack = array();
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    array_push($stack, $category);              
}

如果购物车中有两种产品,每种产品都有不同的类别,print_r($stack)的输出可能是:数组([0] =&gt;感恩节[1] =&gt;家禽)

无论产品如何,我都需要像这样运行条件语句:

if (in_array( 'T-Shirts', $stack[1] )) echo "True"; else echo "False";

上述条件只是查看数组中的第二项,而不是全部。如何搜索数组中的所有项目?

1 个答案:

答案 0 :(得分:1)

$category = $_product->get_categories();
preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
if ( in_array( 'Pants', $categories[1] ) ) {
?>
    <h2>This product has Pants, and potentially other categories</h2>
<?php
}

$ categories [1]是一个数组,其中每个元素都是一个类别。 in_array()检查数组中所请求的值是否为ANYWHERE。

测试它:

$category = '<a href="linktocategorypage" rel="tag">T-Shirts</a><a href="linktocategorypage" rel="tag">Pants</a>';
preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
$pants = in_array( 'Pants', $categories[1] );
if ($pants) echo "True"; else echo "False";
print_r($categories[1]);

的产率:

True

Array
(
    [0] => T-Shirts
    [1] => Pants
)

<强>更新

与您的代码集成:

$stack = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
    foreach( $categories[1] as $cat) $stack[] = $cat;  // Could also use array_merge here
}

if( in_array( 'Pants', $stack ) ) echo 'We have pants';
else echo 'We do not have pants';

如果您不希望某个类别在$ stack数组中出现多次:

$stack = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
    foreach( $categories[1] as $cat) {
        if ( !in_array( $cat, $stack ) ) $stack[] = $cat;
    }
}

if( in_array( 'Pants', $stack ) ) echo 'We have pants';
else echo 'We do not have pants';