pepes Posted November 17, 2009 Share Posted November 17, 2009 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. Quote Link to comment Share on other sites More sharing options...
genericnumber1 Posted November 17, 2009 Share Posted November 17, 2009 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; // ... } ?> Quote Link to comment Share on other sites More sharing options...
pepes Posted November 18, 2009 Author Share Posted November 18, 2009 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 Quote Link to comment Share on other sites More sharing options...
genericnumber1 Posted November 18, 2009 Share Posted November 18, 2009 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. Quote Link to comment Share on other sites More sharing options...
pepes Posted November 18, 2009 Author Share Posted November 18, 2009 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. Quote Link to comment Share on other sites More sharing options...
genericnumber1 Posted November 18, 2009 Share Posted November 18, 2009 Try something like... <?php $uniqueItems[(string)$items[$i]->ItemAttributes->Title] = &$items[$i]; ?> It won't work if it's not a final node though. Quote Link to comment Share on other sites More sharing options...
pepes Posted November 18, 2009 Author Share Posted November 18, 2009 Try something like... <?php $uniqueItems[(string)$items[$i]->ItemAttributes->Title] = &$items[$i]; ?> It won't work if it's not a final node though. It worked Thank you so much, genericnumber1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.