Jump to content

[SOLVED] Remove Duplicates from SimpleXML Object


pepes

Recommended Posts

Does anybody know how can i remove duplicate entries from an Simplexml Object.

Here is the code:

$xml = simplexml_load_string($response);
foreach ($xml->Items->Item as $res){
        $title = $res->ItemAttributes->Title;
..

 

I want to remove duplicates by $title and display only the first one.

Thanks an advance.

You could just rely on the usual override mechanics of an array and recreate the array with unique values...

 

<?php
$xml = simplexml_load_string($response);

$items = &$xml->Items->Item;
$uniqueItems = array();

for($i = count($items)-1; $i >= 0; --$i) {
   $uniqueItems[$items[$i]->ItemAttributes->Title] = &$items[$i];
}

foreach($uniqueItems as $item) {
    $title = $item->ItemAttibutes->Title;
    // ...
}
?>

Thank you for your quick response, genericnumber1

 

There is a little problem when i use the code, i get the error "Illegal offset type in" on line   

$uniqueItems[$items[$i]->ItemAttributes->Title] = &$items[$i];

 

Do you know what could be wrong?

Thanks again

What is the type of $xml->Items->Item->ItemAttributes->Title? I assumed it was just a string. If it's an array or another object, you'll need to use a different method.

 

Yes, it is a string. I thought using trim(), but then it will display just one product no matter what.

 

The code  is actually from a script that pulls products from Amazon api, but i get many duplicates with it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.