第三维数组删除重复项 php

third dimensional array remove duplicates php

如何从 PHP 中的三维数组中删除重复值?

示例数组:

array:2 [▼
  0 => array:2 [▼
    0 => array:92 [▼
      "id_product" => "12"
      "id_supplier" => "0"
      "id_manufacturer" => "2"
    ]
    1 => array:92 [▼
      "id_product" => "14"
      "id_supplier" => "0"
      "id_manufacturer" => "2"
    ]
  ]
  1 => array:2 [▼
    0 => array:92 [▼
        "id_product" => "16"
        "id_supplier" => "0"
        "id_manufacturer" => "2"
    ]
    1 => array:92 [▼
        "id_product" => "14"
        "id_supplier" => "0"
        "id_manufacturer" => "2"
    ]
    ]
]

我期望的数组

 array:2 [▼
      0 => array:2 [▼
        0 => array:92 [▼
          "id_product" => "12"
          "id_supplier" => "0"
          "id_manufacturer" => "2"
        ]
        1 => array:92 [▼
          "id_product" => "14"
          "id_supplier" => "0"
          "id_manufacturer" => "2"
        ]
      ]
      1 => array:2 [▼
        0 => array:92 [▼
            "id_product" => "16"
            "id_supplier" => "0"
            "id_manufacturer" => "2"
        ]
    ]
 ]

我试了array_unique但还是一样

$new_products = array_unique($accessories, SORT_REGULAR);

我尝试了很多东西,很多功能,但还是一样。

此脚本将完全按照您的要求执行

<?php

$input = [
    [
        [
        "id_product" => "12",
        "id_supplier" => "0",
        "id_manufacturer" => "2"
        ],
        [
        "id_product" => "14",
        "id_supplier" => "0",
        "id_manufacturer" => "2"
        ]
    ],
    [
        [
            "id_product" => "16",
            "id_supplier" => "0",
            "id_manufacturer" => "2"
        ],
        [
            "id_product" => "14",
            "id_supplier" => "0",
            "id_manufacturer" => "2"
        ]
    ]
];
$inputCopy = $input; 
$serializedData = [];
foreach ($input as $keyFirstLayer => $valueFirstLayer) {
    foreach ($valueFirstLayer as $keySecondLayer => $valueSecondLayer) {
        $serializedValueSecondLayer = serialize($valueSecondLayer);
        if (in_array($serializedValueSecondLayer, $serializedData)) {
            unset($inputCopy[$keyFirstLayer][$keySecondLayer]);
        } else {
            $serializedData[] = $serializedValueSecondLayer;
        }
    }
}

print_r($inputCopy);

输出

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id_product] => 12
                    [id_supplier] => 0
                    [id_manufacturer] => 2
                )
            [1] => Array
                (
                    [id_product] => 14
                    [id_supplier] => 0
                    [id_manufacturer] => 2
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [id_product] => 16
                    [id_supplier] => 0
                    [id_manufacturer] => 2
                )
        )
)

我首先用两个 foreach 进入第三层,然后制作一个包含序列化元素数组的 $serializedData 数组,然后尝试通过使用此数组检查元素数据来唯一化数组