Link.FYI

Pastebin

Create New My Pastes

Code (PHP) pasted on 2018-11-18, 22:08 Raw Source

  1. <?php
  2. function mergeIntersectingArrays($input) {
  3.     $workArray = array_map(function ($e) {
  4.         $r = new stdClass();
  5.         $r->values = $e;
  6.         $r->merged = false;
  7.         $r->result = false;
  8.         return $r;
  9.     }, $input);
  10.  
  11.     for ($workKey = 0; $workKey < count($workArray); $workKey += 1) {
  12.         $workElem = $workArray[$workKey];
  13.         if ($workElem->merged) continue;
  14.         for ($searchKey = 0; $searchKey < count($workArray); $searchKey += 1) {
  15.             $searchElem = $workArray[$searchKey];
  16.             if ($searchElem->merged || ($searchKey == $workKey)) continue;
  17.             if (count(array_intersect($workElem->values, $searchElem->values)) > 0) {
  18.                 $workElem->values = array_unique(array_merge($workElem->values, $searchElem->values));
  19.                 $searchElem->merged = true;
  20.             }
  21.         }
  22.         $workElem->result = true;
  23.     }
  24.  
  25.     return array_values(
  26.         array_map(function ($item) {
  27.             return $item->values;
  28.         }, array_filter($workArray, function ($item) {
  29.             return $item->result && !$item->merged;
  30.         })));
  31. }