从多维数组中获取数组中的交集值

Get intersect values in a array from Multi-dimensional 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);

主阵中的子阵可以增加,目前有3个子阵

如何从主数组中获取相交值作为数组。

例如,"Monaco Swarovski"、"Long" 值不应该在相交数组上,因为:这些值不存在于所有子数组中。

输出数组(相交)结构必须类似于主数组格式的子数组。

对于这个主数组,输出应该是这样的:

$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);

因此,只需将相同子数组结构中的值相交即可。

我在Whosebug上尝试了很多方法,但有些方法只适用于两个子数组,有些没有给出完全正确的交集。

我认为我们需要正确使用相交函数来解决问题。

感谢您的帮助。

将所有子数组对应的子数组收集到一个临时数组中,并使用扩展运算符将其提供给array_intersect,你可以这样做:

$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);

https://3v4l.org/0OcbN