使用if in foreach检查现有值?

时间:2015-02-09 14:20:26

标签: php if-statement foreach

我有已有值的数组:

$existingValues = array();

现在我在xml文件中获取了新值(是一个导入脚本)但是我必须避免插入已经存在的值,我的问题是,如何在foreach中检查我从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(),但这不正确。

2 个答案:

答案 0 :(得分:1)

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

$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;

答案 1 :(得分:0)

您可以创建$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

由于您不能使用它,因此您可以删除{{1}}。