首页 > 解决方案 > 如果值等于,则从数组中删除项目

问题描述

在 Woocommerce 订单页面上,我有订单中的项目,我想通过这些项目循环并按产品 id排除特定项目。

$order->get_order_number();
$items = $order->get_items();

foreach( $items as $key => $value) :
     $exclude = $value->get_product_id();
     if( in_array($exclude, array('3404') ) {  
        unset($items[$key]);
     }
  }
endforeach;

$new_items = array_values($items);

我认为这将遍历原始数组,删除$itemwho$product_id == 3404然后重新索引。

我在这里没有运气。有什么想法吗?

解决了->

        //Filter out colon cleanse duo
    $items = array_filter($order->get_items(), function($item) {
        return $item->get_product_id() != 3404;
    });

    //Randomize ids and grab one
    shuffle($items);
    foreach( $items as $item) :

        $product_id = $item->get_product_id();
        $product_name = $item->get_name();

        break;
    endforeach;

标签: phparrayswoocommerceordersunset

解决方案


你应该能够做到这一点:

$items = array_filter($order->get_items(), function($item) {
    return $item->get_product_id() != 3404;
});

这会迭代$items并像foreach每个值一样传递给$item. 如果回调array_filter返回 a true,则该值将被保留否则丢弃。

您甚至可以$order->get_items()直接传入,而无需将项目提取到数组中。

此外,如果您需要排除多个,如您的评论中所要求的,您可以这样做:

$items = array_filter($order->get_items(), function($item) {
    return !in_array($item->get_product_id(), [3404, 6890]);
});

推荐阅读