I have a multidimensional array with numbers. I want to check each array with the rest, if it has more than 1 number match with any array, then remove and push numbers to separate array hold all numbers.
In the example
Array[0]
has 1 & 5 same as Array[2]
then I'll send values (1,2,3,4,5)
of Array[0]
to array $removedNumbers()
and unset.
Also Array[1]
has two match with Array[3]
.
Conclusion: Array[0]
and Array[1]
will be removed and all values go to removedNumbers()
.
My original array has 400 child arrays and for some reason it doesn't process to the end, so I use a loop to keep doing the job. Also I noticed lost numbers from $removedNumbers()
array.
Any idea to fix or improve it?
for ($i = 0; $i < count($MyArray); $i ) {
$n = $i 1;
while ($n < count($MyArray)) {
$match = count(array_intersect($MyArray[$i], $MyArray[$n]));
if ($match > 1) {
for ($k = 0; $k < 5; $k ) {
array_push($removedNumbers, $MyArray[$i][$k]);
}
unset($allTickets[$i]);
$MyArray = array_values($MyArray);
break;
}
$n ;
}
}
Sample data for $MyArray
:
[
[1,2,3,4,5],
[1,6,7,8,9],
[1,5,6,10,11],
[6,12,13,14,15]
]
CodePudding user response:
Loop on the dataset to create a set of elements with indexes of wherever it is present.
Loop again on the dataset again to check with count of each element in the set. If it is greater than 1, it means it is present in more than 1 subarray. If count of such common elements is greater than 1, then add them to
removedNumbers
and unset them from the current array.
Snippet:
<?php
$set = [];
foreach($d as $idx => $val){
foreach($val as $v){
$set[ $v ][ $idx ] = true;
}
}
$removedNumbers = [];
foreach($d as $idx => $val){
$commonElements = 0;
foreach($val as $v){
if(count($set[ $v ]) > 1){
$commonElements ;
unset($set[ $v ][ $idx ]);
}
}
if($commonElements > 1){
unset($d[ $idx ]);
$removedNumbers = array_merge($removedNumbers, $val);
}
}