Skip to content

Instantly share code, notes, and snippets.

@shanecp
Created April 14, 2019 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanecp/5cea18ba04cc5c8b30f55aecb240b5b5 to your computer and use it in GitHub Desktop.
Save shanecp/5cea18ba04cc5c8b30f55aecb240b5b5 to your computer and use it in GitHub Desktop.
Recursive Intersect for array subsets in PHP. Pass an array and a subset of an array. Returns the matching subset if it intersects.
<?php
namespace App\Domain;
class Intersect
{
/**
*
* Is the array an associative array?
*
* @param array $arr
*
* @return bool
*/
public static function isAssocArray(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
/**
*
* Find matching structure on a nested array recursively
*
* @param $subset
* @param $array
* @param array $results
*
* @return array
*/
public static function intersectRecursive($array, $subset, $results = [])
{
$isAssocArray = self::isAssocArray($subset);
if ($isAssocArray) {
// loop each row of array
// iterating through parents
foreach ($subset as $key => $value) {
if ($key) {
if (isset($array[$key])) {
$filteredSource = $array[$key];
//if the value is array, it will do the recursive
if (is_array($value)) {
$loopResults = self::intersectRecursive($subset[$key], $filteredSource, $results);
$results[$key] = $loopResults;
}
}
}
}
} else {
// iterate through final leaf nodes
foreach ($subset as $subsetRow) {
foreach ($array as $sourceRow) {
if (array_intersect($sourceRow, $subsetRow) == $subsetRow) {
$results[] = $subsetRow;
}
}
}
}
return $results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment