I have a question about determining whether a PHP associative array, which contains indices to another array, is a subset of another similarly constructed associative array, namely one that contains indices to another array.
Assuming that I have two arrays, one named dogs and another named legged-animals.
<?php
$dogs = array(0 => array('height' => 100, 'weight' => 100),
1 => array('height' => 50, 'weight' => 50));
$legged-animals = array(0 => array('height' => 200, 'weight' => 500),
1 => array('height' => 220, 'weight' => 500),
2 => array('height' => 100, 'weight' => 100),
3 => array('height' => 50, 'weight' => 50));
?>
So the question is, how can I determine that dogs is a subset of legged-animals?
EDIT: Here's my attempt at finding out whether one is the subset of the other:
function filter($largeSets, $subSets)
{
$result = array();
$count = count($subSets);
foreach ($largeSets as $individualSet)
{
foreach ($subSets as $set)
{
$intersection = array_intersect($individualSet, $set);
if (!empty($intersection) && isset($intersection['height']) && isset($intersection['weight']))
{
$result['array'][] = $individualSet;
$count--;
break;
}
}
}
$result['result'] = ($count == 0);
return $result;
}
UPDATED:
This is a somewhat easier solution that I think will solve the problem. The idea is to go through the multidimensional array, serialize
the arrays, and then use array_intersect
.
$dogs = array(0 => array('height' => 100, 'weight' => 100),
1 => array('height' => 50, 'weight' => 50),
2 => array('height' => 10, 'weight' => 25) );
$legged_animals = array(0 => array('height' => 200, 'weight' => 500),
1 => array('height' => 220, 'weight' => 500),
2 => array('height' => 100, 'weight' => 100),
3 => array('height' => 50, 'weight' => 50));
foreach ($dogs as $dog)
{
$arr[] = serialize($dog);
}
foreach ($legged_animals as $animal)
{
$arr2[] = serialize($animal);
}
$intersection = array_intersect($arr, $arr2);
print_r($intersection);
At this point, the intersection
would print out a serialized form of the intersection. To get the initial results back, you'd have to unserialize
the arrays.
Is there an easier way of doing this?