function array_is_subset($superset, $subset)
{
    if (count($superset) < count($subset)) {
        return false;
    }
    $candidates = $superset;
    $found = 0;
    foreach ($subset as $elem) {
        // the candidates array is empty then we're done
        if (empty($candidates)) {
            break;
        }
        $foundAt = null;
        $attributes = array_keys($elem);
        foreach ($candidates as $key => $candidate) {
            $candidateAttributes = array_keys($candidate);
            if (array_intersect($attributes, $candidateAttributes) != $attributes) {
                continue;
            }
            foreach ($attributes as $attribute) {
                $isArray = is_array($elem[$attribute]);
                if ($isArray && !is_array($candidate[$attribute])) {
                    continue 2;
                }
                if ($isArray) {
                    $ck1 = array_keys($candidate[$attribute])[0];
                    $ek1 = array_keys($elem[$attribute])[0];
                    if (is_array($candidate[$attribute][$ck1]) && is_array($elem[$attribute][$ek1])) {
                        if (!array_is_subset($candidate[$attribute], $elem[$attribute])) {
                            continue 2;
                        }
                        break;
                    }
                    if (array_intersect($elem[$attribute], $candidate[$attribute]) != $elem[$attribute]) {
                        continue 2;
                    }
                }
                if ($candidate[$attribute] != $elem[$attribute]) {
                    continue 2;
                }
            }
            $foundAt = $key;
            break;
        }
        $found += (int) ($foundAt !== null);
        unset($candidates[$foundAt]);
    }
    return $found == count($subset);
}
Esempio n. 2
0
<?php

require 'array_is_subset.php';
$superset = [['id' => 1, 'name' => 'John Doe', 'occupations' => [['Carpenter'], ['doctor']], 'created_at' => '2015-07-01 12:15:43'], ['id' => 2, 'name' => 'Mary Anne', 'occupation' => 'Welder', 'created_at' => '2015-07-05 11:25:41'], ['id' => 3, 'name' => 'Kelly Roberts', 'occupation' => 'Programmer', 'created_at' => '2015-07-07 13:18:52']];
$subset = [['name' => 'Mary Anne', 'occupation' => 'Welder'], ['name' => 'Kelly Roberts', 'occupation' => 'Programmer'], ['name' => 'John Doe', 'occupations' => [['Carpenter']]]];
echo array_is_subset($superset, $subset) ? "Match\n" : "No Match\n";