Im looking the build a new array by finding the intersection of a given array of arrays.
This probably a simple set theory problem for most people but its kind of hard for me to wrap my head around.
So I have a keyed array:
$myArray = [
'array1' => [A, B, C],
'array2' => [A, B, C, D],
'array3' => [A, B, C, D],
'array4' => [D],
]
And the goal is to build an entirely new array keyed in with concatenated keys of the previous array if they have an intersection:
Basically like this:
$newArray = [
'array1,array2,array3' => [A, B, C],
'array2,array3,array4' => [D]
]
Since array1, array2, array3 have ABC in command they will form as one keyed array, same as array2,array3,array4 and so on.
I have tried to experiment with array_intersect but it seems like its not the one that im looking for or perhaps I solving it in a really wrong way. Any ideas is much appreciated.
$myArray = [
'array1' => [A, B, C],
'array2' => [A, B, C, D],
'array3' => [A, B, C, D],
'array4' => [D],
];
$newArray = [];
$keys = array_keys($myArray);
for($i = 0, $size = count($myArray); $i < $size; $i++){
for($k = $i; $k < $size; $k++){
print_r(array_intersect($myArray[$keys[$i]], $myArray[$keys[$k]]));
}
}
//Foal
// 'array1,array2,array3' => [A, B, C]
// 'array2,array3,array4' => [D]
$newArrayalso contain the key'array1,array4'with value[]and the key'array2,array3'with value[A, B, C, D]etc?array2,array3is not included since all of its elements exist in already inarray1, array2, array3andarray2,array3,array4, although in set theory an empty set is also considered a new entry