SHARE
TWEET

Untitled

a guest Apr 24th, 2019 51 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3.  
  4. namespace App\Domain;
  5.  
  6.  
  7.  
  8. class Intersect
  9. {
  10.  
  11.     /**
  12.      *
  13.      * Is the array an associative array?
  14.      *
  15.      * @param array $arr
  16.      *
  17.      * @return bool
  18.      */
  19.     public static function isAssocArray(array $arr)
  20.     {
  21.         if (array() === $arr) return false;
  22.         return array_keys($arr) !== range(0, count($arr) - 1);
  23.     }
  24.  
  25.  
  26.     /**
  27.      *
  28.      * Find matching structure on a nested array recursively
  29.      *
  30.      * @param       $subset
  31.      * @param       $array
  32.      * @param array $results
  33.      *
  34.      * @return array
  35.      */
  36.     public static function intersectRecursive($array, $subset, $results = [])
  37.     {
  38.         $isAssocArray = self::isAssocArray($subset);
  39.  
  40.         if ($isAssocArray) {
  41.             // loop each row of array
  42.             // iterating through parents
  43.             foreach ($subset as $key => $value) {
  44.                 if ($key) {
  45.                     if (isset($array[$key])) {
  46.                         $filteredSource = $array[$key];
  47.  
  48.                         //if the value is array, it will do the recursive
  49.                         if (is_array($value)) {
  50.                             $loopResults = self::intersectRecursive($subset[$key], $filteredSource, $results);
  51.                             $results[$key] = $loopResults;
  52.                         }
  53.                     }
  54.                 }
  55.             }
  56.         } else {
  57.             // iterate through final leaf nodes
  58.             foreach ($subset as $subsetRow) {
  59.                 foreach ($array as $sourceRow) {
  60.                     if (array_intersect($sourceRow, $subsetRow) == $subsetRow) {
  61.                         $results[] = $subsetRow;
  62.                     }
  63.                 }
  64.             }
  65.         }
  66.  
  67.         return $results;
  68.     }
  69.  
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top