使用 if in foreach 检查现有值?

Check for existing values with if in foreach?

我的数组已经存在值:

$existingValues = array();

现在我在 xml 文件中获得了新值(是一个导入脚本),但我必须避免插入已经存在的值,我的问题是,我如何在我列出的 foreach 中执行 if 检查来自 xml?

的所有新值
$i = 1;

foreach($node->children() as $child) :
    $attribute2 = $child->attributes();
    $productcode = $attribute2['sku'];
    $productvariant = $attribute2['variantid'];
    $productprice = $attribute2['price'];

    if ($attribute2['sku']) :
        echo $productcode . ' - ' . $productvariant . '<br>';
    endif;

    $i++;      
endforeach;

我试过 in_array() 但不正确。

您可以创建一个存储产品的数组并测试当前产品是否已在该数组中:

$i = 1;
$products = array();

foreach($node->children() as $child) :
    $attribute2 = $child->attributes();
    $productcode = $attribute2['sku'];
    $productvariant = $attribute2['variantid'];
    $productprice = $attribute2['price'];

    if ($attribute2['sku'] && !in_array($productcode, $products)) :
        echo $productcode . ' - ' . $productvariant . '<br>';
    endif;

    $products[] = $productcode;

    $i++;      
endforeach;

您可以创建一个 $existingSKU 数组,从现有元素中提取 sku。然后你可以比较当前的 sku 和现有的,如果不存在,你可以添加元素到现有的。

// build existing sku array
$existingSKU = array();
foreach($existingValues as $value)
{
    array_push($existingSKU, $value['sku']);
}

// add element to existing, if not present
foreach($node->children() as $child)
{
    $attribute2 = $child->attributes();

    if(!in_array($attribute2['sku'], $existingSKU))
    {
       array_push($existingValues, $attribute2);
    }
}

既然不用,可以去掉$i