首页 > 解决方案 > 如何在样本数组中查找重复值

问题描述

如何使用php在示例数组中查找重复值

Array
(
    [id] => 644
    [qty] => 1
    [product] => 127
    [super_attribute] => Array
        (
            [140] => 16
        )

)
Array
(
    [id] => 648
    [qty] => 1
    [product] => 111
    [super_attribute] => Array
        (
            [140] => 18
        )

)
Array
(
    [id] => 652
    [qty] => 1
    [product] => 111
    [super_attribute] => Array
        (
            [140] => 18
        )

)

在上面的数组中,我想找到重复的 [product] => 111 和 [140] => 18 。我怎样才能做到这一点?

标签: phparraysmagento

解决方案


一种可能的方法是将您要查找的两个元素组合成一个较长的键,然后创建一个二维数组,列出所有具有新键的 ID。

在下面的代码中,我将product数字乘以 1000,添加 的值super_attribute[140]并将结果转换为字符串。根据您对正在使用的数据的了解,还有其他方法可以获得新密钥。

<?php
$arr  = [
    [

    "id" => 644,
    "qty" => 1,
    "product" => 127,
    "super_attribute" => [
        "140" => 16
        ]
    ],

    [
    "id" => 648,
    "qty" => 1,
    "product" => 111,
    "super_attribute" => [
        "140" => 18
        ]
    ],
    [
        "id" => 652,
        "qty" => 1,
        "product" => 111,
        "super_attribute" => [
            "140" => 18
        ]
    ]
];

$dup = [];

foreach($arr as $subArr) {
    // Calculate the new combined key
    $newKey = (string)($subArr['product']*10000+$subArr["super_attribute"][140]);

    // If we don't have this new key, create an array with the ID,
    // otherwise, add the ID to the existing array for the new key.
    if (isset($dup[$newKey])) {
        $dup[$newKey][] = $subArr['id'];
    } else {
        $dup[$newKey] = [$subArr['id']];
    }
}

var_dump($dup);

输出:

array (size=2)
  1270016 => 
    array (size=1)
      0 => int 644
  1110018 => 
    array (size=2)    //IDs with the combined key 111 and 18
      0 => int 648    
      1 => int 652

推荐阅读