I have this array
$data = json_decode('[
[
["Monaco Chain"],
["Monaco Diamond Cut","Monaco Plain","Monaco Swarovski"],
["11.50 mm","13.50 mm","15.50 mm","17.50 mm","6.50 mm","8.00 mm","9.50 mm"],
["18.00","20.00","22.00","24.00","26.00","28.00","30.00","7.00","7.50","7.75","8.00","8.25","8.50","9.00","7.25","8.75","9.50","16.00","9.25"],
["ROSE","WHITE","YELLOW"],
["10","14","18","21"],
["New","Long"],
["No","Yes","N/A"],
["No","Yes","N/A"]
],
[
["Monaco Chain"],
["Monaco Diamond Cut","Monaco Plain"],
["6.50 mm"],
["16.00","18.00","20.00","22.00","24.00","26.00","28.00","30.00","7.50","8.00","9.00"],
["ROSE","WHITE","YELLOW"],
["10","14","18","21"],
["New"],
["No","Yes","N/A"],
["No","Yes","N/A"]
],[
["Monaco Chain"],
["Monaco Diamond Cut","Monaco Swarovski"],
["11.50 mm","13.50 mm","15.50 mm","17.50 mm","6.50 mm","8.00 mm","9.50 mm"],
["18.00","20.00","22.00","24.00","26.00","28.00","30.00","7.00","7.50","7.75","8.00","8.25","8.50","9.00","7.25","8.75","9.50","16.00","9.25"],
["ROSE","WHITE","YELLOW"],
["10","14","18","21"],
["New","Long"],
["No"],
["No","Yes"]
]
]
', true);
The subarrays in the main array can be increase, for now there are 3 sub arrays.
How can I get just intersect values as array from the main array.
For example, "Monaco Swarovski", "Long" value should not be on intersect array, because: these values are not exist in all sub arrays.
The output array (intersect) structure must like a sub array on main array format.
For this main array, the output should be this:
$data = json_decode('
[
[
["Monaco Chain"],
["Monaco Diamond Cut"],
["6.50 mm"],
["18.00","20.00","22.00","24.00","26.00","28.00","30.00","7.50","8.00","9.00"],
["ROSE","WHITE","YELLOW"],
["10","14","18","21"],
["New"],
["No"],
["No","Yes"]
]
]', true);
So, just intersect values in same sub array structure.
I tried so many methods on stackoverflow, but some of them were only working for two sub arrays, some of them did not give exactly the right intersection.
I think we need to use intersect functions correctly for the solution.
Thanks for your helps.
Gathering the corresponding sub-sub-arrays for all sub-arrays in a temporary array, and using the spread operator to feed that to array_intersect, you could do it like this:
$subArrayCount = count($data);
$subSubArrayCount = count($data[0]);
$result = [];
for($i=0; $i<$subSubArrayCount; ++$i) {
$temp = [];
for($j=0; $j<$subArrayCount; ++$j) {
$temp[] = $data[$j][$i];
}
$result[] = array_intersect(...$temp);
}
var_dump($result);