Merge structure, add only unique items

I’m trying to merge two structures into a new one. I started from the snippet provided here.

If works fine, except that some items appear multiple times. Is there a way to add only an item to the new structure if it isn’t already present?

Thanks a ton.

Here’s my code:

<?php
class EventsPage extends Page {
  public function listSpeakers($type) {

    // list relevant children
    $scope = $this->children()->find($type)->index();

    // instantiate a new structure object
    $structure = new Structure();

    $key = 0;

    // loop through the pages collection
    foreach($scope as $p) {

      //loop through the structure object of each page
      foreach($p->speakers()->toStructure() as $item) {

        // get relevant speaker page
        $speaker = page('speakers')->children()->find($item->name()->value());

        // append each entry to the new structure object
        $structure->append($key, $speaker);

        $key++;
      }
    }

    return $structure;
  }
}

This. looks a bit weird. If you are adding pages, a collection would be a better fit than a structure object.

This would also solve your issue. with the duplicates automatically.