0

I have array with already existing values:

$existingValues = array();

now i get new values in xml file (is a import script) but i have to avoid insert of already existing values, my question is, how can i do a if check in foreach where i list all new values from 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;

I tried with in_array() but it's not correct.

2
  • How do you identify elements? I can see that every element has some fields (sku, variantid, price). What is the id of each element? sku maybe? Commented Feb 9, 2015 at 14:25
  • Ahh sorry, yes i have to check sku, if sku from array and sku from xml is the same then ignore... Commented Feb 9, 2015 at 14:27

2 Answers 2

1

You can create an array wich stores the products and test if the current product is already in the 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;
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a $existingSKU array, extracting sku from existing elements. Then you can compare current sku with existing, and if not present, you can add element to existing.

// 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);
    }
}

Since you don't use it, you can remove $i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.