如何删除数组中的匹配值

问题描述

我正在遍历两个数组。 $wooProducts$data。两个数组看起来相同并且包含 WooCommerce 产品。

我的目标是遍历 $wooProducts 并从 $data删除匹配的产品。 除了 unset() 部分,一切正常。知道如何让它工作吗?我也试过这个:unset($data[$matchedProduct]);

// Find function
function find($array,$key) {
    foreach ($array as $product) {
        if ($product["Name"] == $key) {
            return $product;
        }
    }
}

$updateProducts = [];
// Check if product already exist
foreach ($wooProducts as $wooProduct) {
    $matchedProduct = find($data,$wooProduct->post_title);
    if ($matchedProduct) {
        array_push($updateProducts,$matchedProduct);
        unset($data[$wooProduct]); // <---- Not working
    }
}

解决方法

您可以使用 array_search() 查找索引,然后您可以使用 unset。

array_search($wooProduct->post_title,$data);